So I want to create a basic C application mysort that takes a list of files, reads each of them line by line into a buffer and sorts the lines alphabetically. The code looks something likes this (plus parameter parsing, etc):
//How do I initialize an array of 1024byte-Strings with an unknown amount of fields?
char** lines;
int lineNum = 0;
for(int num_files = j; num_files < argc; num_files++){ //iterate through all files
FILE * filepointer ;
char * line = NULL;
size_t len = 0;
ssize_t read;
filepointer = fopen(argv[num_files], "r");
if (filepointer == NULL)
exit(EXIT_FAILURE);
//TODO: write each line into a new spot of the array, this try doesn't work!
while ((read = getline(&line, &len, filepointer)) != -1) {
//the lines may be assumed to be a max of 1024 bytes
lines[lineNum] = malloc(1024 * sizeof(char));
//lines[lineNum] = line;
strcpy(lines[lineNum], line);
lineNum++;
}
fclose(fp);
if (line)
free(line);
//These values might be wrong, but that isn't the issue I'm adressing
//just for illustration
qsort(lines , argc - 1, sizeof(char *), cmpstringp)
//do something with the sorted lines
}
Since I have to use qsort(3), I need to produce a char** holding all the lines at some point.
What's a good way to accomplish such a task? Do I need my own data structure in order to dynamically store several identical objects?
The lines char** Array isn't initialized here, so the program doesn't work. But since the number of lines is completely unknown at the start of the program it may not be explicitly defined (Unless you know a clever function to figure this out)
The only ways I figured out so far is defining my own dynamic datastructure (e.g. LinkedList) or to parse all files twice in order to determine the number of lines that will be produced.
Both seem very un-elegant to me, but maybe I'm just not accustomed to C code.
lines[lineNum] = malloc(...);lines[] is still uninitialised at this point.