fopen Function

fopen <stdio.h>

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

Used to open a file with given filename. Whether or not this function opens an existing file or creates a new one, opens it for appending, overwriting or reading or as a binary or text file, depends on the mode string supplied as parameter.

Return Values:

File handle of the file opened, if there was no error, otherwise it returns a NULL pointer.

Mode Strings:

The mode string consists of:
1) A "r", "w" or "a", followed by
2) An optional "b", followed by
3) An optional "+".

Here are the meanings of the different options:

r Open the file for reading.
w Open the file for overwriting. Creates a new file if it doesn't already exist.
a Open the file for appending (i.e. new data is added at the end). Creates a new file if it doesn't already exist.
b Opens the file as a binary file (the default without the "b" is a text file).
+ Open the file for reading and writing.
Binary vs Text Mode:

You would open a file as a text file if you expected it to contain strings of text, terminated with end of line characters. (Actually, in practice, end of line characters are usually stored as some sort of carriage return/line feed combination in the actual file itself, depending on the operating system. However C essentially interprets these as end of line characters \n.) Examples of text files include script files, programming source files and other files containing `human readable' text.

If the file contains fields of data, e.g. integers, floating point numbers, data in proprietry format, sound, video or picture data, etc, then you would open the file in binary mode by including a "b" in the mode string. Instead of reading the data in one string at a time (with say fgets), you would then read it in, a certain number of bytes at a time (with say fread).

Example:
#include <stdio.h>

int main(void)
{
    char buffer[256];
    FILE * myfile;
	
    myfile = fopen("some.txt","r");
	
    while (!feof(myfile))
    {
        fgets(buffer,256,myfile);
        printf("%s",buffer);
    }
	
    fclose(myfile);
    
    return 0;
}

This example opens a file called some.txt for reading as a text file, then in a loop, reads lines from the file and outputs them to the screen until the end of file comes.

top
Home / Return to Function Reference