Hi, I'm very new to programming and am taking an entry-level course in C. One of the homework problems we have is to take two text files, merge them into a third file, and sort the file alphabetically. I think that I've written a code to merge the files, although I haven't tested it yet because he hasn't given us the address of the files - once I have more of the code written I'll make my own files to test it. The part that I can't get is the sorting. I know how to sort arrays alphabetically, but I don't know how to get the file into an array in the first place. This is made harder by the fact that we don't know how long the list is (our program is supposed to work no matter what files he gives us). Here is what I have so far, can anybody give me some guidance on how to proceed? Thank you!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
main() {
FILE *fp1, *fp2, *fp3;
//merge documents into one list (list names are placeholders)
fp1 = fopen(list1.txt, "r");
fp2 = fopen(list2.txt, "r");
fp3 = fopen(mergelist.txt, "w");
while (fgets(str, 80, fp1)){
fprintf("%s\n", str);
close(fp1);
}
while (fgets(str, 80, fp2)){
fprintf(%s\n", str);
close(fp2);
}
close(fp3)
//count how many lines are in the new list
fp3 = fopen(mergelist.txt, "r")
int i, j, k;
i=0;
while(fgets(str, 80, fp3)){
i++;
}
//make an array long enough to hold the entire list
float x[i];
Once the text is an array, I'm planning on using this to sort it alphabetically:
Code:
for (j=0; j<i-1; j++) {
for(k=j+1; k<i; k++) {
if(strcmp(x[j], x[k])!=0 swap(&x[j], &x[k]);
}
}
}
int swap(char x[], char y[]) {
char tmp[20];
strcpy(tmp, x);
strcpy(x, y);
strcpy(y, tmp);
}