Introduction to C / C++ Programming
Basic Text File Input and Output

Accreditation

Some content here was drawn from "C Programming, A Modern Approach" by K.N. King, Chapter 22.

Some material on this page was drawn from linuxmanpages.com

Binary versus Text Data Storage

Basics of Reading and Writing Text Files

In order to read from or write to simple text files, three steps are needed:

  1. Open the file using fopen
  2. Read from the file using fscanf or write to the file using fprintf
  3. Close the file using fclose.

fopen

FILE *fopen(const char *path, const char *mode);

fprintf and fscanf

int fprintf(FILE *stream, const char *format, ...);

int fscanf(FILE *stream, const char *format, ...);

fclose

int fclose(FILE *stream); 

Example:

    char filename[ 80 ];
    FILE *inputFile;
	int data;

	printf( "Please enter a file name: " );
	scanf( "%s", filename );
	if( ( inputFile = fopen( filename, "r" ) ) == NULL ) {
		fprintf( stderr, "Error- Unable to open %s\n", filename );
		exit( -1 );
	}

	if( fscanf( inputFile, "%d", &data ) != 1 ) {
		fprintf( stderr, "Error reading from %s\n", filename );
		exit( -2 );
	}

	printf( "Successfully read in %d from %s\n", data, filename );

	fclose( inputFile );
	inputFile = NULL;  // Safety precaution, to prevent trying to use a closed file.
    

 

See also: Formatted I/O