fopen()

Declaration

FILE* fopen(const char* kcpFilename, const char* kcpMode);

Description:

This function is used to open a file for input and/or output. The argument "fcpFilename" designates the name of the file to be opened, and "kcpMode" designates the type of access that is requested. If the file is successfully opened, the function returns a pointer to the FILE object. Otherwise a NULL pointer is returned.


Mode StringMode Description

"a"This opens the file for writing at the end of the file (appending) or it creates a new file if it does not already exist.
"a+"This opens the file for writing at the end of the file (appending) or it creates a new file if it does not already exist. It also opens the file for reading.
"r"This opens a file for reading only. The file must exist prior to opening.
"r+"This opens a file for read and writing. The file must exist prior to opening.
"w"This opens a file for writing only. If the file exists, it is erased when opened.
"w+"This opens a file for reading and writing. If the file exists, it is erased when opened.
"b"This opens a file in binary mode as opposed to the default ASCII text mode.
"ccs"This opens a file in UNICODE text mode.

Example

#include <cstdio>

int main()
{
    char* cpFileName = "XoaX.txt";
    // Open an ASCII text file for reading
    FILE* qpFile = fopen(cpFileName, "r" );

    // Check that the file was opened successfully.
    if (!qpFile) {
        printf("Could not open %s for reading \n",  cpFileName);
        return 1;
    }

    char caBuffer[50];
    // Read in the first and only line of text
    char* cpReturn = fgets(caBuffer, 50, qpFile);
    if (cpReturn) {
        printf("Read in: %s\n", caBuffer);
    }

    fclose(qpFile);

    return 0;
}

Input File:

fopen() Input File

Output:

fopen() Output