File Input and Output in C

In order to read information from a file, or to write information to a file, your program must take the following actions. 1) Create a variable to represent the file. 2) Open the file and store this "file" with the file variable. 3) Use the fprintf or fscanf functions to write/read from the file.

File I/O in C

File I/O in C is very similar to Matlab. There are two main differences. One, we have to type the FILE variable. Two, we read one value (or a single line of values) at a time, whereas by default in Matlab, you may read many values at once.

The basic steps for using a File in C are always the same:

  1. Create a variable of type "FILE*".

  2. Open the file using the "fopen" function and assign the "file" to the variable.

  3. Check to make sure the file was successfully opened by checking to see if the variable == NULL. If it does, an error has occured.

  4. Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop. In the case of reading data, usually, the data is read in and placed in an array, but sometimes we process the data "on the fly" (i.e., we do not store the data, we process it and create a result directly before reading any more data.

Example Code

Here are examples of the basic syntax for opening a file and writing to or reading from it:

        

          FILE *in_file  = fopen("name_of_file", "r"); // read only
          FILE *out_file = fopen("name_of_file", "w"); // write only
          
          // test for files not existing.
          if (in_file == NULL || out_file == NULL)
            {  
              printf("Error! Could not open file\n");
              exit(-1); // must include stdlib.h
            }
          
          // write to file vs write to screen
          fprintf(file, "this is a test %d\n", integer); // write to file

          fprintf(stdout, "this is a test %d\n", integer); // write to screen 
          printf(         "this is a test %d\n", integer); // write to screen 

          // read from file/keyboard. remember the ampersands! 
          fscanf(file, "%d %d", &int_var_1, &int_var_2); 

          fscanf(stdin, "%d %d", &int_var_1, &int_var_2); 
          scanf(        "%d %d", &int_var_1, &int_var_2);
          
        
      

Here is a comparison between reading from a file in Matlab and in C:

C Language

            
          //
          //
          // C code to read a bunch of integers from a file...
          //
          //

          int number;

          FILE* in_file = fopen("name_of_file", "r"); // read only 
        
          if (! in_file ) // equivalent to saying if ( in_file == NULL )
             { 
                printf("oops, file can't be read\n");
                exit(-1);
             }

          // attempt to read the next line and store
          // the value in the "number" variable
          while ( fscanf(file, "%d", & number ) == 1 ) 
             {
               printf("We just read %d\n", number);
             }
            
          

Matlab

            
          %
          % Matlab code to read a bunch of integers from a file...
          % using fopen and fscanf.  See the Matlab topic of textread
          % to see how to accomplish this much more easily
          %



          in_file = fopen('name_of_file', 'r'); % read only

          if (in_file == -1)
            error('oops, file can''t be read');
          end


          [number, count] = fscanf(file, '%d', 1);

          while (count == 1) % while we have read a number
            fprintf('We just read %d\n', number);

            [number, count] = fscanf(file, '%d', 1); % attempt to read the next number
          end
            
          

FGETS function: Read One Line at a Time

To read one line from a file (or the keyboard) at a time, use the fgets function.

	
	  char line[100];
	  fgets( line, 100, stdin );    // stdin - keyboard
	
      

fgets places the "\n" (newline) at the end of the line. Thus if we type in "hello", what really goes into the variable line is [ 'h', 'e', 'l', 'l', 'o', '\n', '\0' ]

fgets returns the keyword null on error. Thus we often use:

        
          char line[100];
          while ( fgets( line, 100, stdin ) != null )
            {
              fprintf("The line is: %s\n", line);
            }
        
      

Back to Topics List