当写入文件时,中间数据存储在fopen()和fclose()之间? [英] While writing into a file , Where intermediate data stored in between fopen() and fclose()?

查看:199
本文介绍了当写入文件时,中间数据存储在fopen()和fclose()之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Below is a small program which takes information from user and write it into a file teacher.txt. I am using only one array q2[30] for taking input and writing into a file using fprintf(). But when i want to enter more teacher then again loop will execute but at this time fclose() will not appear so data will not be write/save(don't know) into file also previous value of q2 get erased/overwrite with new input. So in this case where data is stored/write by fprintf().Because when i manually open teacher.txt before fclose() there is no any new data.

#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打开文件时,写入的输出为 buffered ,这意味着它实际上并未发送到较低层直到缓冲区已满或您用fflush显式刷新它.

When you open a file with fopen, the output you write is buffered, meaning it's not actually send to the lower layers until the buffer is either full or you explicitly flush it with fflush.

还请注意,fopen/fprintf/fclose下的层(一直到实际硬件)可能具有一定的缓冲作用,可能会延迟磁盘上的数据.

Also note that the layers under fopen/fprintf/fclose, all the way down to the actual hardware, may also have some buffering that can delay the actual update of the on-disk data.

这篇关于当写入文件时,中间数据存储在fopen()和fclose()之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆