gpt4 book ai didi

c - 在 C 中简单搜索文件

转载 作者:行者123 更新时间:2023-11-30 17:38:30 25 4
gpt4 key购买 nike

我正在学习用 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 (要求输入书名),然后简单地返回到主函数,而不搜索任何内容。

最佳答案

您的代码似乎效率低下,我不知道为什么您在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com