我正在学习用C语言编程,并且正在研究一个小项目:一个图书馆管理软件。我遇到的问题是使搜索功能正常工作。我知道如果我处理大量数据,我的代码确实非常简单且效率低下,但是既然不是这样,我认为它应该可以工作。
这是我写的功能:
void search_for_book (FILE *BooksFile) {
BooksFile = fopen("Data.txt", "a+");
char book_title[100], test_book[100], author[100], category[100];
int answer, status, more_books;
more_books: // To search for more books
printf("Type the title of the book you would like to look for:\n");
scanf("%s", book_title);
while(!feof(BooksFile)){
fscanf(BooksFile, "%s", test_book);
if(strcmp(book_title, test_book) == 0) { // strcmp returns zero if strings are equal
printf("The book you informed was found.\n");
printf("Do you want to see its information? Type 1 for yes and 2 for no.\n");
scanf("%d", &answer);
if (answer == 1) { // User wants information
fscanf(BooksFile, "%s", author);
fscanf(BooksFile, "%s", category);
fscanf(BooksFile, "%d", &status);
printf("Book's title: %s\n", book_title);
printf("Book's author: %s\n", author);
printf("Book's category: %s\n", category);
printf("Book's status: %d\n", status);
break;
} else { // User doesn't want information
printf("Would you like to search for another book? Type zero if that's the case.\n");
scanf("%d", &more_books);
if (more_books == 0) {
goto more_books;
}
break;
}
}
}
}
我的代码有什么问题,我该如何解决?当我调用此函数时,该程序仅执行printf(要求键入书名),然后简单地返回到main函数,而不搜索任何内容。
最佳答案
您的代码似乎效率低下,我不知道为什么要在search_for_book
函数中传递文件指针,而您可以在本地使用并打开它。我对您的功能做了一些修改,尝试一下。
void search_for_book()
{
FILE *BooksFile;
BooksFile = fopen("Data.txt", "r");
char book_title[100], test_book[100], author[100], category[100];
int answer, status, more_books;
while(1)
{
printf("Type the title of the book you would like to look for:\n");
scanf("%s", book_title);
while(!feof(BooksFile))
{
fscanf(BooksFile, "%s", test_book);
if(strcmp(book_title, test_book) == 0)
{
printf("The book you informed was found.\n");
printf("Do you want to see its information? Type 1 for yes and 2 for no.\n");
scanf("%d", &answer);
if (answer == 1)
{
// User wants information
fscanf(BooksFile, "%s", author);
fscanf(BooksFile, "%s", category);
fscanf(BooksFile, "%d", &status);
printf("Book's title: %s\n", book_title);
printf("Book's author: %s\n", author);
printf("Book's category: %s\n", category);
printf("Book's status: %d\n", status);
break;
}
}
}
rewind(BooksFile);
printf("Would you like to search for another book? Type zero if that's the case.\n");
scanf("%d",&more_books);
if(more_books == 1)
continue;
else
break;
}
}
关于c - 在C中简单搜索文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22114049/