Closing Files
Files are closed using the fclose function. The syntax is as follows:
fclose(in);
Reading Files
The feof function is used to test for the end of the file. The functions fgetc, fscanf, and fgets are used to read data from the file.
The following example lists the contents of a file on the screen, using fgetc to read the file a character at a time.
#include <stdio.h>
int main()
{
FILE *in;
int key;
if ((in = fopen("tarun.txt", "r")) == NULL)
{
puts("Unable to open the file");
return 0;
}
while (!feof(in))
{
key = fgetc(in);
/* The last character read is the end of file
marker so don't print it */
if (!feof(in))
putchar(key);
}
fclose(in);
return 0;
}
The fscanf function can be used to read different data types from the file as in the following example, providing the data in the file is in the format of the format string used with fscanf.
fscanf(in, "%d/%d/%d", &day, &month, &year);
The fgets function is used to read a number of characters from a file. stdin is the standard input file stream, and the fgets function can be used to control input.
|