In computer programming, the fopen
function is one of the basic functions in the C programming language. It returns an I/O stream attached to the specified file or other device from which reading and writing can be done. Because the functionality is so useful, many languages derived from C provide functions of the same name, with the same or similar function: for example, PHP. fopen
is considered higher-level than the open
system call of UNIX operating systems. The related C library function freopen
performs the same operation after first closing any open stream associated with its parameter.
They are defined as
FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fildes, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);
The fdopen
function is not standard in C89 or C99, but is an extension used in POSIX environments and imitated elsewhere.
The mode parameter is a string that begins with one of the following sequences:
mode | description | starts.. | ||
---|---|---|---|---|
r | rb | open for reading | beggining | |
w | wb | open for writing (creates file if it doesn't exist). Deletes content and overwrites the file. | beggining | |
a | ab | open for appending (creates file if it doesn't exist) | end | |
r+ | rb+ | r+b | open for reading and writing | beggining |
w+ | wb+ | w+b | open for reading and writing. Deletes content and overwrites the file. | beggining |
a+ | ab+ | a+b | open for reading and writing (append if file exists) | end |
The 'b' has no affect on the operation, but is included for clarity. It stands for binary. [1]
The C standard gives two kinds of files - text files and binary files — although operating systems may or may not distinguish between the two. A text file is a file consisting of text arranged in lines with some sort of distinguishing end-of-line character or sequence (in Unix, a bare linefeed character; in the Macintosh OS, a bare carriage return; on DOS and Microsoft Windows, a carriage return followed by a linefeed). When bytes are read in from a text file, an end-of-line sequence is usually mapped to a linefeed for ease in processing. When a text file is written to, a bare linefeed is mapped to the OS-specific end-of-line character sequence before writing. A binary file is a file where bytes are read in "raw," and delivered "raw," without any kind of mapping.
A convenient, but non-standard, way to find the length of a file in C is:
#include <stdio.h> int main() { int length; FILE *f = fopen("filename", "r"); fseek(f, 0L, SEEK_END); length = ftell(f); rewind(f); fclose(f); printf("%d\n", length); return 0; }