c - 写入文件时,fopen() 和 fclose() 之间的中间数据存储在哪里?

标签 c fopen file-handling fclose

下面是一个小程序,它从用户那里获取信息并将其写入文件teacher.txt。 我只使用一个 array q2[30] 获取输入并使用 fprintf() 写入文件。 但是当我想输入更多的老师然后再次循环将执行但是此时 fclose() 不会出现 因此数据不会被写入/保存(不知道)到文件中,q2 的先前值也会被新输入删除/覆盖。 因此,在这种情况下,数据由 fprintf() 存储/写入。因为当我在 fclose() 之前手动打开 teacher.txt 时,有没有任何新数据。

#include <conio.h>
#include <iostream.h> 

int main()
{
 system("cls");
 int yoe;
 char cond[]="yes";char q2[30];

 FILE *p;
 p = fopen("teacher.txt","a+"); //opening file in reading + appending mode
 printf("\nDo you want to add more Teacher ? (yes/no)\n");
 gets(q2);
 fflush(stdin);
 if(!strcmp(q2,cond))
 {
     do
     {
         printf("\nEnter Teacher's Name\n");
         gets(q2);
         fprintf(p,"\n!%s!",q2);
         printf("Enter Teacher's Qualifications\n");
         fflush(stdin);
         gets(q2);
         fprintf(p,"%s!",q2);
         printf("Enter Teacher's year of experience (0-30)\n");
         fflush(stdin);
         scanf("%d",&yoe);
         fprintf(p,"%d!",yoe);
         printf("Enter Teacher's Mobile number(id) [Should be of 10 digits]\n");
         fflush(stdin);
         gets(q2);
         fprintf(p,"%s!",q2);
         printf("\nDo you want to add more Teacher ? (yes/no)\n");
         fflush(stdin);
         gets(q2);
     }while(!strcmp(q2,cond));  // condition to check , if user want to add more Teacher , if yes then loop will execute again.
     fclose(p);  // when user enter 'no' then only fclose will appear.
 }
 fclose(p);printf("\nPress any key to return to Admin menu\n");
 getch();
 system("pause");
}

最佳答案

当您使用 fopen 打开文件时,您写入的输出是缓冲,这意味着它实际上不会发送到较低层,直到缓冲区已满或您明确用 fflush 刷新它。

另请注意,fopen/fprintf/fclose 下的层,一直到实际硬件,可能 有一些缓冲可以延迟磁盘数据的实际更新。

关于c - 写入文件时,fopen() 和 fclose() 之间的中间数据存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31072636/

相关文章:

python - 在 Python 中使用 "Permission denied"函数时出现 "fopen"错误

ruby-on-rails - 如何从 URL 下载文件并将其保存在 Rails 中?

c++ - WIN32API : owner-drawn button creates white background around the text when clicked

CreateThread x3000 返回标准输出句柄

C : Deleting only one node from a doubly linked list

c - 指针不正确计数 [C]

c - 如何用 C 语言读取文本文件中的字母?

c - 如何在 while 循环中打开依赖于尚未声明的信息的文件?

java - Java 编程中的文件处理

c++ - 无法在 Socket 编程中将 int 从服务器发送到客户端