Syntax
#include <stdio.h> FILE *fopen(const char *filename, const char *mode);Description
fopen opens the file specified by filename. mode is a character string specifying the type of access requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.
The possible values for the positional parameters are:
Mode
Warning: Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files of the same name will be lost.
Text files contain printable characters and control characters organized into lines. Each line ends with a new-line character, except for the last line, which does not require one. The system may insert or convert control characters in an output text stream.
Note: Data output to a text stream may not compare as equal to the same data on input.
Binary files contain a series of characters. For binary files, the system does not translate control characters on input or output.
When you open a file with a, a+, ab, a+b or ab+ mode, all write operations take place at the end of the file. Although you can reposition the file pointer using fseek or rewind, the write functions move the file pointer back to the end of the file before they carry out any operation. This action prevents you from overwriting existing data.
When you specify the update mode (using + in the second or third position), you can both read from and write to the file. However, when switching between reading and writing, you must include an intervening positioning function such as fseek, fsetpos, rewind, or fflush. Output may immediately follow input if the end-of-file was detected.
The keyword parameters are:
blksize=value
F
memory This parameter identifies this file as a memory file that is accessible only from C programs. This is the default.
The Developer's Toolkit compiler does not support record I/O.
fopen generally fails if parameters are mismatched.
The file attributes can be altered only if the open mode specified with the fopen function is one of the write modes (w, w+, wb, or wb+). The system deletes the existing file and creates a new file with the attributes specified in fopen.
fopen returns a pointer to a file structure that can be used to access the open file. A NULL pointer return value indicates an error.
This example attempts to open a file for reading.
#include <stdio.h> int main(void) { FILE *stream; if (NULL == (stream = fopen("myfile.dat", "r"))) printf("Could not open data file\n"); else fclose(stream); /* The following call opens a fixed record length file */ /* for reading and writing in record mode. */ if (NULL == (stream = fopen("myfile.dat", "rb+, lrecl=80, blksize=240, recfm=f, type=record"))) printf("Could not open data file\n"); else fclose(stream); return 0; /**************************************************************************** The output should be: Could not open data file ****************************************************************************/ }Related Information