File I/O

Requires the preprocessor directive:

 

#include <stdio.h>

 

Requires a file pointer:

 

FILE *file-variable-name ; // sets up a pointer for the file to be opened

 

FILE is provided from stdio.h

 

When the pointer is declared the target file can be opened and assigned to the file-variable-name

 

file-variable-name = fopen( target-file-name, mode ) ;

Mode Description
r Opens an existing text file for reading
w Opens or creates a text file for writing. If file exists, truncate to zero length, else create
a Opens or creates a text file for writing from end of file, appending to any existing data
rb Opens an existing binary file for reading
wb Opens or creates a binary file for writing. If file exists, truncate to zero length, else create
ab Opens or creates a binary file for writing from end of file, appending to any existing data

 

FILE *filePointer ; //declares a variable pointer called filePointer

 

filePointer = fopen( "C:target-file.txt", "w" ) ; //target-file.txt is now open in write mode, and assigned to filePointer

 

Data can now be written to the file via filePointer:

 

fprintf( filePointer, "Here's some data being written to a text file" ) ;

 

The file must then be closed:

 

fclose( filePointer ) ;

 

Compile & Run produces a file called target-file.txt, that contains the text "Here's some data being written to a text file."

 


 

fgets() and fputs() can also be used to read/write data to/from the Standard Streams, or a file

 

fgets(name, size-of-name,file) //where file could be stdin

fputs(string, file) //where file could be stdout

 

This simple program reads text entered from the keyboard and prints it back out on the screen:

 

A variation on the above, using a file to store the data in:

 

Another variation, reading data from a file and displaying it on the screen:

 

 


*Note: the <stdio.h> fscanf() function has not been explained since it felt to be generally unreliable seeing that it can only read preceding characters up to the first space character, any characters after the space are ignored and it is for that reason that it is thought to be inappropriate for use in a general purpose robust file reader.

Leave a Reply