Course contentsShow
← C
Lesson 709 of 1,21910. Input and OutputFree lesson

Opening files with fopen

Opening files with fopen

What you'll learn: How to use the fopen function to establish a connection between your C program and a file stored on your computer.

The digital handshake

Before your program can read a single word from a text file or save data to a document, it needs to ask the operating system for permission to access that file. Think of fopen as a digital handshake. You are telling the computer, "I want to talk to this specific file, and here is how I plan to behave."

In C, we manage this connection using a special pointer called a FILE pointer. You don't need to know the complex inner workings of the FILE structure yet; just think of it as a "bookmarker" that tracks where you are in the file and whether the connection is healthy.

Using the fopen function

The fopen function requires two pieces of information, both provided as strings:

  1. The Filename: The name (and path) of the file you want to open.
  2. The Mode: How you intend to use the file (e.g., "r" for reading or "w" for writing).

If the "handshake" is successful, fopen returns a pointer to the file. If something goes wrong—like the file doesn't exist or you don't have permission to see it—it returns NULL.

#include <stdio.h>

int main() {
    // 1. Declare a FILE pointer
    FILE *filePointer;

    // 2. Attempt to open "notes.txt" for reading ("r")
    filePointer = fopen("notes.txt", "r");

    // 3. Check if the file was opened successfully
    if (filePointer == NULL) {
        printf("Could not open the file. It might be missing!\n");
    } else {
        printf("File opened successfully! Ready to read.\n");
        
        // (Later lessons will show how to read and close the file)
    }

    return 0;
}

Common modes to remember

While there are several modes, you will use these two most often:

  • "r" (Read): Opens an existing file. If the file isn't there, it fails.
  • "w" (Write): Creates a new file. Warning: If a file with that name already exists, C will delete its contents and start fresh.

Always check for NULL after calling fopen. It is the programming equivalent of making sure a door is actually unlocked before trying to walk through it.

Key takeaway

Use FILE *fp = fopen("filename.txt", "mode"); to connect to a file, and always verify the pointer isn't NULL before proceeding.