What is the output of the below code?
#include <stdio.h>
FILE *filepointer;
char data[100];
void main()
{
filepointer = fopen("talent.txt","r");
while(!feof(filepointer))
{
fgets(data,50,filepointer);
puts(data);
}
fclose(filepointer);
printf("File operation completed");
}
--------------------------------------------------------
The above code tests below scenarios:
1. Declaration of file pointer
2. file operations and functions - fopen, feof, fclose, fgets
3. file operations and functions - Reading the file
----------------------------------------------------------
FILE is a data type used to work on files.
A pointer to files named filepointer is declared
fopen opens the required file and returns a pointer to that file
As the access is mentioned as 'r' in the function, the file must be already present. If the file doesn't exist then NULL is returned
As the execution enters while loop, checks the feof()
feof() is END OF FILE indicator, which returns non-zero if the End of file (EOF) indicator is set, else zero is returned.
If the file is not present, the loop shall run in infinite as EOF shall not be returned forever
If the file is already present, fgets() is used to read the contents of the file
fputs() is used to output the contents of the file
Once the while loop is exited, the fclose() is used to clear the buffers. There are additional check mechanisms which can be implemented to code if fclose() has properly closed the file or not based on the return value.
1 Comments
diamond craft, Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me.
ReplyDelete