I'm trying to compare two .txt files line-by-line. From the two files, I want to print a third .txt file with all the strings of the first two files, without any repeats and in alphabetical order. When I try running the code I get a segmentation fault for the qsort.
The way I went about this was storing each file in an array of strings, then comparing the arrays. I decided to store the currents array into the outputs array to start, then compare the inputs array and store any strings that are unique to the inputs array. When I try to alphabetize my outputs array, I get a seg fault. All memory is freed correctly. All files can open.
static int Comp(const void* a, const void* b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
void comparison(char** inputs, int in_file_len, char** currents, int
curr_file_len, FILE* output_file)
{
int out_file_len = in_file_len + curr_file_len;
char** outputs = malloc(sizeof(*outputs) * out_file_len);
for(int i = 0; i < out_file_len; i++)//allocate memory for outputs
{
outputs[i] = malloc(sizeof(**outputs) * 100);
outputs[i] = "zzzz\n";
}
for(int m = 0; m < curr_file_len; m++)//store the current file
{
strcpy(outputs[m], currents[m]);
}
int x = curr_file_len; //outputs place holder
for(int j = 0; j < in_file_len; j++)
{
for(int k = 0; k < curr_file_len; k++)
{
if(strcmp(inputs[j], currents[k]) == 0)
{
k = curr_file_len;
}
else if(k == (curr_file_len - 1))
{
strcpy(outputs[x], inputs[j]);
x++;
}
}
}
qsort(outputs, out_file_len, sizeof(**outputs) * 100, Comp);
for(int n = 0; n < out_file_len; n++)
{
if(strcmp(outputs[n], "zzzz\n") == 0)
{
free(outputs[n]);
}
else
{
fprintf(output_file, "%s", outputs[n]);
free(outputs[n]);
}
}
free(outputs);
}
I expect there to be a new .txt file created from the outputs array that has all the strings from the first two .txt files in alphabetical order without repeats.