PDA

View Full Version : Output Question of File



anon10364
22-11-2012, 11:59 PM
Sir,

what will be the content of 'file.c' after executing the following program?

int main()
FILE *fp1, *fp2;
fp1=fopen("file.c","w");
fp2=fopen("file.c", "w");
fputc('A', fp1);
fputc('B', fp2);
return 0;

The output of the question is A but I am not able to understand how it is coming.

Thanks,

Anon10364

anup
23-11-2012, 09:29 AM
Anon10364,

In this case you are not closing the files explicitly, however, all the open files are automatically closed at program finish (and buffers flushed automatically). The order in which they are closed perhaps is undefined. So, the output may actually be undefined. It is quite interesting. What happens when you have open files at program termination depends on the method in which you terminated your program. In case of buffered IO if you issue an abort buffers will not be flushed.

BTW, if I run this program I get 'A' in the output. However, if we issue fclose before termination, then there is 'B'.

Good question.

Thanks,

Anup