fopen() in C - Source Code Example

In this source code example, we will see how to use the fopen() function in C programming with an example.

fopen() Function Overview

The fopen() function is a way to open a file on your computer from a C program. You can use it to read from or write to files. It's part of the C library <stdio.h>.

Source Code Example

#include <stdio.h>

int main() {
    // Trying to open a file to write
    FILE *filePtr = fopen("sample.txt", "w");

    // Seeing if the file opened right
    if (filePtr == NULL) {
        printf("Oops! Problem opening the file.\n");
        return 1;
    }

    // Writing to the file
    fprintf(filePtr, "Hello, Ram!\n");
    fprintf(filePtr, "This is C programming.\n");

    // Remember to close the file
    fclose(filePtr);

    printf("Finished writing to the file!\n");

    return 0;
}

Output

Finished writing to the file!

Explanation

Here's what we did:

1. We tried to open a "sample.txt" file for writing.

2. Checked if the file opened without issues. If there was a problem, we let you know.

3. We then wrote two messages to the file.

4. Finally, we closed the file to save what we wrote.

When you run this, you should see a "sample.txt" file with our messages.


Comments