fopen() in C

In C Language, "fopen()" is a function used to open a file.

It's part of the standard input/output library "stdio.h".

This function opens a file and returns a pointer to a "FILE" object which can then be used for subsequent operations on the file.

Syntax:

#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

"filename": This is a C string containing the name of the file to be opened. It can be either an absolute or relative path to the file.

"mode": This is also a C string indicating the opening mode. It specifies how the file should be opened, whether for reading, writing, appending, etc. The modes include:

  • "r": Open for reading. The file must exist.

  • "w": Open for writing. If the file exists, its contents are erased. If the file doesn't exist, it's created.

  • "a": Open for appending (writing at the end of the file). The file is created if it doesn't exist.

  • "r+": Open for both reading and writing. The file must exist.

  • "w+": Open for both reading and writing, but the existing contents are erased. If the file doesn't exist, it's created.

  • "a+": Open for reading and appending. The file is created if it doesn't exist.

fopen Example:

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("example.txt", "w");

    if (fp == NULL) {
        printf("Error opening the file.\n");
        return 1;
    }

    fprintf(fp, "This is a test file.");
    fclose(fp);

    return 0;
}
  • "example.txt" is the name of the file to be opened, and "w" specifies that it should be opened for writing.

  • If the file doesn't exist, it will be created.

  • The function returns a pointer to a "FILE" structure which is then used to write to the file using "fprintf()".

  • Finally, "fclose()" is used to close the file when done.

  • Always remember to check if "fopen()" returns "NULL" to handle cases where the file couldn't be opened.