在c中的文件中搜索

search in a file in c

file.txt 上的数据如图所示放置。

我的代码是这样的:

int searchBookname()
{
    FILE *myFile=fopen("file.txt","r+");


    if (myFile!=NULL) // file  exists
    {
        char tmp1[512];
        char tmp2[512];

        while(fgets(tmp1,512,myFile)!=EOF)
        {
            puts("Insert the Book Name: ");
            scanf("%s",tmp2);
            if(strstr(tmp1,tmp2)!=NULL){
                printf("the book is found: %s\n\n",tmp1);
            }else{
                puts("\nSorry there was no Match with this name! Maybe Book is not recorded yet :(\n");
            }
        }

    }else{ // file doesn't exist
        puts("\nDatabase is not created yet. Please record a new book to create a simple database\n");
        exit(0);
    }
    fclose(myFile); // closing the file
} 

由于某种原因,它不断跳过 if 语句 2 次,并且在 第三次它打印出正确的结果。 无论我尝试搜索什么书,都会发生这种情况。 参见 here

如何在不跳过 if 语句的情况下找到结果。

很明显。 文件的前两行如下:

Record_Date ...
-> (empty line)

您正在逐行阅读文件,每行中都有支票簿名称。所以 if 必须在前 2 次失败。 如果你想在你的文件中找到一本书,你的做法是不正确的。有不同的方法,但最简单的是将书籍记录读入结构数组,然后在该数组中查找书名。

您逐行阅读文件。所以在第三个 loop/line 中有一个 'book1' 的记录。代码按原样正常工作。也许您想在 while 循环之外询问用户书名,并在每一行中搜索给定的书名。如果有,你可以打印你的消息并退出循环。

int searchBookname()
    {
        FILE *myFile=fopen("file.txt","r+");

        if (myFile != NULL) // file  exists
        {
            char tmp1[512], tmp2[512];

            puts("Insert the Book Name: ");
            scanf("%s",tmp2);

            // Skip the first two lines of the file
            fgets(tmp1,512,myFile);
            fgets(tmp1,512,myFile);

            while(fgets(tmp1,512,myFile) != EOF)
            {
                if(strstr(tmp1,tmp2) != NULL)
                {
                    printf("the book is found: %s\n\n",tmp1);
                    break;
                }
                else
                {
                    puts("\nSorry there was no Match with this name! Maybe Book is not recorded yet :(\n");
                }
            }

        }
        else
        { // file doesn't exist
            puts("\nDatabase is not created yet. Please record a new book to create a simple database\n");
            exit(0);
        }
        fclose(myFile); // closing the file
    }