问题
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");
}
回答1:
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
.
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.
来源:https://stackoverflow.com/questions/31072636/while-writing-into-a-file-where-intermediate-data-stored-in-between-fopen-an