fopen() function in C++

In this guide, you will learn what is fopen() function is in C++ programming and how to use it with an example.

1. fopen() Function Overview

The fopen() function is a part of the <cstdio> library in C++. It is used to open a file and returns a pointer to the file stream associated with that file. If the file opening operation fails, it returns a NULL pointer.


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


- filename: The name of the file to be opened.

- mode: The mode in which the file should be opened (e.g., "r" for reading, "w" for writing, "a" for appending, etc.).

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    // Open a file for writing
    FILE *file = fopen("sample.txt", "w");

    if (file) {
        std::cout << "File opened successfully for writing." << std::endl;
    } else {
        std::cout << "Error in opening the file." << std::endl;

    return 0;


File opened successfully for writing.

3. Explanation

1. We've included the <iostream> header for standard input/output operations and <cstdio> for the fopen() and fclose() functions.

2. We try to open a file named "sample.txt" for writing. If the file does not exist, it will be created. If it already exists, its contents will be truncated.

3. After checking if the file was opened successfully, we close it using the fclose() function.