C programming stdio.h function - FILE *fopen(const char *filename, const char *mode)

‮w‬ww.theitroad.com

In C programming, the stdio.h header file provides a set of functions for performing input and output operations on streams of data. One of the most commonly used functions in this header file is fopen(), which opens a file with a specified filename and mode.

The fopen() function takes two arguments:

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

The first argument, filename, is a pointer to a string that specifies the name of the file to be opened. The second argument, mode, is a pointer to a string that specifies the mode in which the file should be opened.

The mode string can be one of the following:

  • "r": Open for reading (file must exist).
  • "w": Open for writing (file is created or truncated).
  • "a": Open for appending (file is created if it does not exist).
  • "r+": Open for reading and writing (file must exist).
  • "w+": Open for reading and writing (file is created or truncated).
  • "a+": Open for reading and appending (file is created if it does not exist).

The fopen() function returns a pointer to a FILE object that represents the opened file. If an error occurs, the function returns a null pointer.

Here's an example of how to use fopen() to open a file:

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("example.txt", "w");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    /* Do something with the file */

    fclose(fp);

    return 0;
}

In the above example, the fopen() function is used to open a file named "example.txt" in write mode. If the file cannot be opened, the message "Error opening file." is printed to the console. Otherwise, the file is used for whatever purpose is needed (not shown in this example), and then closed with the fclose() function.