I/O to and from files
Similar statements also exist for handling I/O to and from files. The statements are #include <>
FILE *fp;
fp = fopen(name, mode);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );
The logic here is that the code must - define a local ``pointer'' of type FILE (note that the uppercase is necessary here), which is defined in <>
- ``open'' the file and associate it with the local pointer via fopen
- perform the I/O operations using fscanf and fprintf
- disconnect the file from the task with fclose
The ``mode'' argument in the fopen specifies the purpose/positioning in opening the file: ``r'' for reading, ``w'' for writing, and ``a'' for appending to the file. Try the following:
#include <>
void main()
{
FILE *fp;
int i;
fp = fopen("foo.dat", "w"); /* open foo.dat for writing */
fprintf(fp, "\nSample Code\n\n"); /* write some info */
for (i = 1; i <= 10 ; i++) fprintf(fp, "i = %d\n", i); fclose(fp); /* close the file */ }
No comments:
Post a Comment