File I/O

The FILE type

  1. When working with files in C, declare a FILE variable
  2. The FILE variable needs to be a pointer, because it is a pointer to a file
Example:
FILE *myfile;

Associate the variable with a file

  1. Use fopen()
  2. Specify the file path and the mode
  3. If successful, fopen returns a file pointer
  4. If fopen fails, NULL is returned
  5. Below are valid modes
"r" Reading; if file does not exist, fopen fails
"w" Writing; if file exists, contents are destroyed
"a" Appending; does not remove original EOF marker; creates a new file if needed
"r+" Reading and writing; file must exist
"w+" Reading and writing; opens an empty file
"a+" Appending; moves the EOF marker; creates a new file if needed

Example:
myfile = fopen("c:\\boot.ini", "r");

Testing for EOF

  1. To check for the end of the file, use feof(file)
  2. Included in stdio.h
  3. Returns true when EOF

Writing / Reading by single character

  1. To read in or write out text by line, use getc() and putc()
  2. getc (inputfile) returns the char, or EOF
  3. putc (char, outputfile);
  4. Both in stdio.h

Writing / Reading by line of text

  1. To read in or write out text by line, use fgets() and fputs()
  2. fgets (textbuffer, maxchars, inputfile); // returns NULL to indicate an error or EOF
  3. fputs (buffer, output_file);
  4. Both in stdio.h

fprintf() and fscanf()

  1. Work like printf and scanf, except with files
  2. Both in stdio.h
Examples:
fprintf(outputfile, "My age is %d\n", myAge);
fscanf(inputfile, "%f", &floatVariable);


Close the files

  1. Use fclose() when you are finished working with the files
  2. Syntax: fclose(file)

A sample program


/*

  Read in a text file and output another text file
  that has the contents of the first text file with
  line numbers

*/

#include <stdio.h>


int main()
{

	char buffer[100];	// a variable for the strings we read in
	int counter = 1;	// used for line numbers

	FILE *inputfile;	// a pointer to the input file
	FILE *outputfile;	// a pointer to the output file

	inputfile = fopen("c:\\test1.txt", "r");	// open text1.txt


	// Before going on, make sure the input file opened properly
	if(inputfile != NULL)
	{
		outputfile = fopen("c:\\test2.txt", "w");	// open text2.txt

		// While there are lines in input file, read them in, append a number
		// and output the results to outputfile
		while (fgets(buffer, 100, inputfile))
		{
			fprintf(outputfile, "%d. %s", counter, buffer);
			counter++;
		}

		// close the files
		fclose(inputfile);
		fclose(outputfile);
	}

	else
		printf("Error opening input file.\n");




	return 0;
}