I'm developing an application and one of the functions is the function sort_books_file which basically has to sort the name of the books in the file fp by alphabetical order and then prints them in the file fp2.
At the moment, the only thing the function does is printing the name of the books from file fp into file fp2.
I would like to know how it is possible to sort the name of the books by alphabetical order into the file fp2.
I'm a C beginner and I don't have a lot of experience in C programming...somebody helps?
#include <stdio.h>
FILE *fp;
FILE *fp2;
struct book{
int key;
char name[50];
int price;
};
sort_books_file(){
struct book b;
//r: open the file for reading (read-only)
if ((fp=fopen("books.dat","r"))==NULL){
printf("Error\n");
exit(1);
}
//w: open the file for writing (write-only).
//the file is created if it doesn't exist
if ((fp2=fopen("books_sorted.dat","w"))==NULL){
printf("Error: not possible to open the file. \n");
exit(1);
}
//while end of file has not been reached
while (!feof(fp)){
fread(&b,sizeof(b),1,fp);
if(feof(fp))
{
break;
}
fwrite(&b.name,sizeof(b.name),1,fp2);
}
fclose(fp);
fclose(fp2);
}