13.1. fopen()

Opens a file for reading or writing

Prototypes

#include <stdio.h>

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

Description

The fopen() opens a file for reading or writing.

Parameter path can be a relative or fully-qualified path and file name to the file in question.

Paramter mode tells fopen() how to open the file (reading, writing, or both), and whether or not it's a binary file. Possible modes are:

r

Open the file for reading (read-only).

w

Open the file for writing (write-only). The file is created if it doesn't exist.

r+

Open the file for reading and writing. The file has to already exist.

w+

Open the file for writing and reading. The file is created if it doesn't already exist.

a

Open the file for append. This is just like opening a file for writing, but it positions the file pointer at the end of the file, so the next write appends to the end. The file is created if it doesn't exist.

a+

Open the file for reading and appending. The file is created if it doesn't exist.

Any of the modes can have the letter "b" appended to the end, as is "wb" ("write binary"), to signify that the file in question is a binary file. ("Binary" in this case generally means that the file contains non-alphanumeric characters that look like garbage to human eyes.) Many systems (like Unix) don't differentiate between binary and non-binary files, so the "b" is extraneous. But if your data is binary, it doesn't hurt to throw the "b" in there, and it might help someone who is trying to port your code to another system.

Return Value

fopen() returns a FILE* that can be used in subsequent file-related calls.

If something goes wrong (e.g. you tried to open a file for read that didn't exist), fopen() will return NULL.

Example

int main(void)
{
    FILE *fp;

    if ((fp = fopen("datafile.dat", "r")) == NULL) {
        printf("Couldn't open datafile.dat for reading\n");
        exit(1);
    }

    // fp is now initialized and can be read from

    return 0;
}

See Also

fclose()
freopen()