C语言读写文件

Read and write from file in C langage

拜托,有人可以为我解释为什么这个程序不起作用吗? 我正在尝试使用 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 %d year 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)

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

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

问题是您在写入文件句柄后尝试读取文件句柄。

fichier 就像编辑器中的光标,它在文件中只有一个位置。当您使用 r+ 打开文件时,fichier 位于文件的开头。当您打印到 fichier 时,它会覆盖文件开头的任何内容。然后,当您尝试阅读时,它会从打印停止的地方开始阅读。

例如,如果我开始 test.txt 并在其中添加一些文本,具体来说,将打印的内容不止这些。

$ cat test.txt
First line
Second line
Third line

然后我运行程序。

$ ./test
give your age ? 41
rd line

注意它打印了 rd line 因为那是它写 Hello you have 41 year old.

之后剩下的
$ cat test.txt
Hello you have 41 year oldrd line

我不确定你想要完成什么,但你可能需要 fseek 将光标移动到正确的位置。


附带说明,将整个程序包装在 if (fichier != NULL) 中很尴尬。如果文件没有打开,您也不会收到错误消息,它会悄悄地、神秘地什么都不做。相反,检查错误、显示信息性消息并退出程序。

#include <string.h>
#include <errno.h>
#include <stdlib.h>

char file[] = "test.txt";
FILE *fichier = fopen(file, "r+");
if (fichier == NULL) {
    fprintf(stderr, "Could not open '%s' for r+: %s\n", file, strerror(errno));
    exit(1);
}

这称为 early exit and makes code much, much simpler. By taking care of errors immediately, the code can follow a happy path,无需总是嵌套在条件语句中。