请有人能帮我解释一下为什么这个程序不起作用?
我正在尝试使用 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/