What is Files in C explain with program and example

What is Files in C explain with program and example

Files are the most common form of a stream.
The first thing we must do is open a file. The function fopen() does this:
   FILE *fopen(char *name, char *mode)
fopen returns a pointer to a FILE. The name string is the name of the file on disc that we wish to access. The mode string controls our type of access. If a file cannot be accessed for any reason a NULL pointer is returned.

Modes include: ``r'' -- read,
         ``w'' -- write and
         ``a'' -- append.
To open a file we must have a stream (file pointer) that points to a FILE structure.
So to open a file, called myfile.dat for reading we would do:

  FILE *stream, *fopen();
         /* declare a stream and prototype fopen */

         stream = fopen(``myfile.dat'',``r'');


it is good practice to to check file is opened
correctly:

         if ( (stream = fopen( ``myfile.dat'',
                        ``r'')) == NULL)
                 {  printf(``Can't open %s n'',
                         ``myfile.dat'');
                  exit(1);
                 }
         ......

Labels: