我正在开发一个应用程序,其中一个函数是sort_books_file函数,它基本上必须按字母顺序对文件fp中的书名进行排序,然后将它们打印在文件fp2中。
目前,该功能唯一的功能是将文件名称从文件fp打印到文件fp2中。
我想知道如何按字母顺序将书籍名称排序到文件fp2中。
我是C初学者,我在C编程方面没有很多经验......有人帮忙吗?
#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);
}
答案 0 :(得分:2)
最简单的方法是使用book.name上的strcmp()进行排序。
strcmp()的工作原理如下:
语法:int strcmp(const char *str1, const char *str2)
st1和str2是要比较的字符串
如果str1小于str2,则函数返回 -1 ;如果字符串相等,则返回 0 ;如果str1大于str2,则返回 1
strcmp()使用词典排序,这意味着它会对字典中显示的单词进行排序。 Here's一个讨论它的问题。
<强>实施例强>
strcmp("hello", "world")
返回-1
strcmp("world", "hello")
返回1
stcmp("boo", "boo")
返回0
这是一个排序功能,可以做你想要的(我还没有测试过):
void sort_books_file(){
//Assume you have only maximum 10 books
struct book books[10];
strct book b;
//open files for reading and writing
//..
//..
int i = 0;
while (!feof(fp)){
fread(&b,sizeof(b),1,fp);
books[i] = b;
i++;
if(feof(fp))
{
break;
}
}
//number of books
int len = i;
//bubble sort;
int j = 0;
//Bubble sort. Google for "bubble sort"
for(i=0; i<len; i++)
{
for(j=0; j<len-1; j++)
{
//If the first book should come after the next book in the array
if(strcmp(books[j].name, books[j+1].name) > 0)
{
//swap the books
struct book temp;
temp = books[j];
books[j] = books[j+1];
books[j+1] = temp;
}
}
}
//now write each book in the array "books" into the file one by one
}
答案 1 :(得分:2)
我希望这会有所帮助:
void sort(struct book* books, int n)
{
int j,i;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(books[j].name < books[j+1].name)
{
struct book temp = books[j];
books[j] = books[j+1];
books[j+1] = temp;
}
}
}
}
将图书信息存储到图书结构的数组中。然后将此数组传递给 sort 函数。这将完成你的工作。
struct book LIST[n];
sort(LIST, n);