Credits

Sunday, March 15, 2009

C's File and Input Stream: Writing

We can use the streams or a sequence of data and types of C to allow us to read and/or write records to a an external file. This allows us to write a more database-oriented applications.

We can use C's basic commands with files. Only affix f to these commands. For instance, to print to a file is to use fprintf(), to read is to use fscanf().Further, we instruct our C on the actions we shall perform with the file. We indicate "w" to write, "r" to read and "a" to append to a file.

Check the sample program.

Click the link to view/hide more.

[+/-] show/hide



#include stdio.h /*enclose this in <> */
main()
{
FILE *MYFILE;
if ((MYFILE=fopen("mysample.txt","w"))!=NULL) /*creating a file named mysample.txt*/
{ fprintf(MYFILE,"Welcome to file handling in C!\n"); /*writing to the file*/
fclose(MYFILE); /*closing the file*/
}
else
printf("Error writing mysample.txt!");
return 0;
}

AddThis