home
C TUTORIALS

Files


The C I/O system supplies a consistent interface to the programmer independent of the actual device being accessed. That is, the C I/O system provides a level of abstraction between the programmer and the device. This abstraction is called a stream, and the actual device is called a file. A file may be called a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. Using C programming, we can perform a number of operations on files in secondary storage.
You associate a file with a stream by opening it through open function. If the file can support position requests, opening that file also initializes the file position indicator to the start of the file. As each character is read from or written to the file, the position indicator is incremented, ensuring progression through the file.
You disassociate a file from a specific stream with a close operation. If you close a file opened for output, the contents, if any, of its associated stream are written to the external device. This process, generally referred to as flushing the stream, guarantees that no information is accidentally left in the disk buffer.


In the coming sections, we will learn about:


The File Pointer


The file pointer is the common thread that unites the C I/O system. A file pointer is a pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, and the current position of the file. The file pointer identifies a specific file and is used by the associated stream to direct the operation of the I/O functions. To use a file pointer, the following statement is used:

FILE *fp;
Here, fp is the name of the file pointer.


Opening a File


To open a file and link it with a stream, use the function fopen(). This returns the file pointer to that file. The prototype of fopen() is

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

The different modes in which a file can be opened are
Mode Meaning
r Open a text file for reading
w Open a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Open a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or Create a text file for read/write
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or Create a binary file for read/write

For an example :
fp=FILE *fopen ("Student.dat","r");
If an error occurs while opening the file, then the pointer points to a NULL value.


Closing a File


The function fclose() closes a stream that was opened using fopen(). It writes any data still remaining in the disk buffer to the file. It also frees the file control block associated with the stream, making it available for reuse. The prototype of this function is

int fclose(FILE *fp);
where fpis the file pointer returned by the call to fopen(). This reurns zero for a successful close operation, while it reaturns EOF (enf of file : A special character, whose ASCII value is 26, signifies end of file) for an unsuccessful one.

Writing to a File

The C I/O system defines two equivalent functions that output a character. They are putc( ) and fputc( ). These functions write a character to a file. The syntax is:

int putc(int ch, FILE *fp);
where fp is the file pointer returned by fopen( ), and ch is the character to be written. A successful putc() operation returns the character written, while an unsuccessful one returns EOF. The function fputs() is used to output a string to the output stream referenced to by the file pointer. The syntax is:
int fputs( const char *s, FILE *fp );
where fp is the file pointer returned by fopen( ), and s is the string to be written. It returns a non-negative value on success. Otherwise, EOF is returned. Also, fprintf() is used to send formatted output to a stream as shown below:
int main(void) { FILE *fp; int i; fp = fopen("results.dat", "w"); if (fp == NULL) { printf("I couldn't open results.dat for writing.\n"); exit(0); } for (i=0; i<=10; ++i) fprintf(fp, "%d, %d\n", i, i*i); return 0; }
fprintf() works exactly in the same manner as printf() except the first argument is the file pointer, fp which points to the file we're writing to.

Reading from a File

The C I/O system defines two equivalent functions that read a character. They are getc( ) and fgetc( ). They read a character from the file opened. The syntax of getc() is :

int getc(FILE *fp);

where fp is the file pointer returned by fopen( ). This returns an integer when the character is read and an EOF when the end of file has been reached or when an error occurs. Hence to read the end of file, the following code is used:

do { ch = getc(fp); } while(ch!=EOF);
The function to read a string from a file is fgets(). Following is its syntax:
char *fgets(char *str, int n, FILE *stream)
This reads from the specified stream and stores the string in a string pointed to by str. This reads till either (n-1) characters, or a new line feed character or the end of file, whichever comes first and appends a null character to terminate the read string. An example for reading from a file and displaying on the screen:
#include <stdio.h> main( ) { FILE *fp ; char s[80] ; fp = fopen ( "POEM.TXT", "r" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } while ( fgets ( s, 79, fp ) != NULL ) printf ( "%s" , s ) ; fclose ( fp ) ; }
This program reads from a file named "POEM.TXT", stores in string s and displays the latter.

Erasing a File

The remove( ) function erases the specified file. Its syntax of the function is:

int remove(const char *filename);
It returns zero if successful. Otherwise, it returns a non-zero value.