Sunday, March 15, 2009

C's File and Input Stream: Reading

In the previous lecture on files and streams, we had written a sample program to write. But we have to open this file created in any text editor to view the file contents. But, reading from a file is also possible. We simply provide the file option "r" to indicate file reading.

Check the sample program in C.

Click the link to view/hide more.

[+/-] show/hide

#include stdio.h /*enclose this in <> */
char text[80]; /*holds the content of the file*/
if ((MYFILE=fopen("mysample.txt","w"))!=NULL) /*creating a file named mysample.txt*/
{ if (fgets(text,sizeof(text),MYFILE)!=NULL)
printf("Your file contains %s",text);
fclose(MYFILE); /*closing the file*/
else printf("There is an error reading mysample.txt!\n");
printf("Error opening mysample.txt!\n");

No comments: