c - C语言对文件的读写

标签 c file fgets

请有人能帮我解释一下为什么这个程序不起作用? 我正在尝试使用 r+ 从文件中读取和写入。文件test.txt存在并且写入正确执行。但是,读取不起作用。

int main() {

    FILE* fichier = NULL;
    int age, TAILLE_MAX=10;
    char chaine[TAILLE_MAX];

    fichier = fopen("test.txt", "r+");
    if (fichier != NULL)
    {

        printf("give your age ? ");
        scanf("%d", &age);
        fprintf(fichier, "Hello you have %d year old", age);

        while (fgets(chaine, TAILLE_MAX, fichier) != NULL)
        {
            printf("%s", chaine); //does not print
        }fclose(fichier);
    }

    return 0;
}

通过不起作用我的意思是它不显示任何东西!即使文件中包含一些“你已经...岁”的句子。没有错误。只是程序不打印文件内容

最佳答案

您正在同时写入和读取文件, 这不是一个好的做法, 但您的代码不起作用的原因是缓冲。在 fclose(fichier) 语句发生之前,fprintf(fichier, "Hello you have %dyear old",age); 可能不会发生。 我将这两个语句添加到您的代码中,请参见下文。 另外,一旦您执行了 fprintf ,您的文件指针 fichier 就不在文件末尾,这是您尝试执行的下一件事的错误位置,即读取 age 你刚刚写的数字,所以你必须以某种方式将文件指针 fichier 向后移动 - 我刚刚使用了 rewind 如果 test 它将工作.txt 是一个新创建的文件。否则,您将需要某种方法将文件指针 fichier 向后移动,足以读取您刚刚编写的内容。

int main() {

FILE* fichier = NULL;
int age, TAILLE_MAX=10;
char chaine[TAILLE_MAX];

fichier = fopen("test.txt", "r+");
if (fichier != NULL)
{

    printf("give your age ? ");
    scanf("%d", &age);
    fprintf(fichier, "Hello you have %d year old", age);

    fflush( fichier );  /* force  write to FILE */
    rewind( fichier );  /* rewind FILE pointer to beginning */

    while (fgets(chaine, TAILLE_MAX, fichier) != NULL)
    {
        printf("%s", chaine); //does not print
    }
}
fclose(fichier);
return 0;
}

在你的原始代码中,声明

while (fgets(chaine, TAILLE_MAX, fichier) != NULL)

无法读取任何内容并返回 NULL,因此 printf("%s", chaine); 不会发生。发生这种情况是因为输出缓冲和 fprintf() 语句在您认为应该发生时没有发生。

此输出缓冲是正常的,如果您希望在该时刻发生 printf,那么您需要使用 fflush() 阅读此处了解更多信息:Why does printf not flush after the call unless a newline is in the format string?

关于c - C语言对文件的读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43286435/

相关文章:

c - 使用 getc 和 putc 打印文件内容

python - 什么时候需要在 Python 中关闭文件?

file - 从输入读取后如何写入文本文件?

C:while循环退出条件,使用fgets进行输入

c - 字符串比较循环问题

c - 如何在c中搜索文本文件中的特定字符串

java - 访问jar中的csv文件

c - CSV存储的大数据数组中的段错误读取

c - 以 EOF 结尾的 fgets 循环会跳过下一个 fgets

c - sum+++i 是 C 中未定义的行为吗?