C PROGRAMMING

File Input And Output

Date Published:
Last Modified:

The standard C library provides functions for writing input and output to files.

Most of the file input/output functions are declared in header stdio.h. Add the line #include <stdio.h> to your source code to use file I/O functions.

fopen()

fopen() is used to open a file.

The function declaration changed in C99, by adding the keyword restrict. Before C99 it was:

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

In C99 and above:

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

where:

filename: Null-terminated string of the filename to associate the data to
mode: Null-terminated string that determines the file access mode
\
modeStands ForDescriptionBehaviour If File Already ExistsBehaviour If File Doesn't Exist
"r"readOpen a file to read from it.Read from start.Error.
"w"writeOpen a file to write to it.Delete file contents.Create new file.
"wx"writeWrite to file, but don't overwrite if file already exists.Error.Create new file
"a"appendOpen a file to append data to the end.Append new data to the end of file.Create new file.
"r+"read extendedOpens a file for read/write accessRead from start.Error.
"w+"write extendedCreates a file for read/write accessDeletes file contents.Create new file.
"w+x"write extendedOpens a file for read/write access, but doesn't overwrite if file already exists.Error.Create new file.
"a+"append extendedOpens a file for read/write accessAppends new data to the end of file.Create new file.
bbinary openOpens a file in binary mode (**Windows only**).??

fopen() returns pointer to opened file stream on success, otherwise a NULL pointer on fail.

You have to be careful when using fopen() on a system with multiple threads, there is the possibility of creating race conditions.


Like this page? Upvote with shurikens!

Tags:

    comments powered by Disqus