C语言 在 txt 文件中逐行读取,如果没有附加到文件的句子,则覆盖



我有一个 txt 文件

[what]
apple = apple is fruits
[who]
steve = steve is a teacher

我假设读取文件,如果输入等于行,它将覆盖。如果没有,它将附加到新行。

以下是我的代码

    char lines[255];
    char question[255];
    char answer[255];
    FILE* f;
    if ((f = fopen("text.file", "a")) == NULL) {
        printf("File not found");
        exit(1);
    }
    scanf("%s", &question);
    while (fgets(lines,255,f)!= NULL) {
        if (lines != question) {
            printf("I dont know. %s", question);
            scanf("%s", &answer);
            fputs(answer, f);
        }
    }
    fclose(f);

我尝试运行,但它只是没有通过 if 语句。为什么会这样?

添加#include <string.h>并替换if (lines != question)

对于if (strcmp(lines, question) != 0).

您不能将字符串与此进行比较: 如果(行!=问题( 替换为: if(strncmp(question,question,strlen(question((!=0(

最新更新