> ~ Online tutorial

Closing a file

A file is closed by calling the function fclose(). fclose() has the syntax:
int returncode;
FILE *fp;

returncode = fclose (fp);

fp is a pointer to the file which is to be closed and returncode is an integer value which is 0 if the file was closed successfully. fclose() prompts the file manager to finish off its dealings with the named file and to close the portal which the operating system reserved for it. When closing a file, a program needs to do something like the following:
if (fclose(fp) != 0)

   printf ("File did not exist.\n");

This is the highest level function which writes to files. Its name is meant to signify "file-print-formatted" and it is almost identical to its stdout counterpart printf(). The form of the fprintf() statement is as follows:
fprintf (fp,"string",variables);

where fp is a file pointer, string is a control string which is to be formatted and the variables are those which are to be substituted into the blank fields of the format string. For example, assume that there is an open file, pointed to by fp:
int i = 12;
float x = 2.356;
char ch = 's';

fprintf (fp, "%d %f %c", i, x, ch);

The conversion specifiers are identical to those for printf(). In fact fprintf() is related to printf() in a very simple way: the following two statements are identical.
printf ("Hello world %d", 1);

fprintf (stdout,"Hello world %d", 1);

The analogue of scanf() is fscanf() and, as with fprintf(), this function differs from its standard I/O counterpart only in one extra parameter: a file pointer. The form of an fscanf() statement is:
FILE *fp;
int n;

n = fscanf (fp,"string",pointers);

where n is the number of items matched in the control string and fp is a pointer to the file which is to be read from. For example, assuming that fp is a pointer to an open file:
int i = 10;
float x = -2.356;
char ch = 'x';

fscanf (fp, "%d %f %c", &i, &x, &ch);

Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
Powered By: BloggerYard.Com