C Programming Language


Working with Files


C provides a range of functions in the header file  stdio.h  for writing to and  reading  from external devices. The external device you would use for storing and retrieving data is typically a disk drive,  but not  exclusively. Because, consistent with the philosophy of C, the library facilities you’ll use for working with files are device independent, they apply to virtually any external storage device.

 

File Streams :

The C library provides functions for reading and writing to or from data streams. A stream is an abstract  representation of any external source or destination for data, so the keyboard, the command line on your display, and files on a disk are all examples of things you can work with as streams. You use the same input/ output functions for reading and writing any external device that is mapped to a stream.

 

File Modes :
Mode Description
"w" Open a text file for write operations. If the file exists, its current contents are discarded.
"a" Open a text file for append operations. All writes are to the end of the file.
"r" Open a text file for read operations.

 

Opening a File

You associate a specific external file name with an internal file pointer variable through a process referred to as opening a file. One way to open a file is by calling the fopen() function that returns the file pointer for a specific external file. There’s a safer alternative function, fopen_s(), which I’ll come to in a moment. The fopen() function is defined in stdio.h, and it has this prototype:

FILE *fopen(const char * restrict name, const char * restrict mode);

 

Write Mode :

If you want to write to an existing text file with the name myfile.txt, you would use this statement:

FILE *pfile = NULL;
char *filename = "myfile.text";
if(!fopen_s(&pfile, filename, "w")) // Open myfile.txt to write it
printf_s("Failed to open %s.\n", filename);

 

Append Mode :

If you want to add to an existing text file rather than overwrite it, you specify mode "a", which is the append mode of operation. This positions the file at the end of any previously written data. If the file doesn’t exist, a new file will be created. If you want to reuse the file pointer you declared previously to open the file to add data to the end, use the following statement:

fopen_s(&pfile, "myfile.txt", "a"); // Open myfile.txt to add to it

 

Read Mode :

If you want to read a file, open it using this statement:

fopen_s(&pfile, "myfile.txt", "r");