Back to course

File I/O Part 2: Opening and Closing Files

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 48: File I/O Part 2: Opening and Closing Files

Opening a File: fopen()

The fopen() function attempts to open a file and associate a stream with it. It returns a FILE * pointer if successful, or NULL on failure.

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

Example: Opening a file for writing

c #include <stdio.h>

int main() { FILE *fp; char filename[] = "output.txt";

// Attempt to open in write mode ('w')
fp = fopen(filename, "w");

if (fp == NULL) {
    perror("Error opening file"); // Helps display system error message
    return 1; // Indicate error
}

printf("File '%s' opened successfully.\n", filename);
// ... file operations ...

return 0; 

}

Closing a File: fclose()

Closing a file disconnects the stream from the file, ensuring any buffered data is written to disk and releasing the FILE structure memory. This is critical to prevent data loss.

Syntax: int fclose(FILE *stream); (Returns 0 on success, EOF on failure).

c if (fp != NULL) { if (fclose(fp) == 0) { printf("File closed successfully.\n"); } else { printf("Error closing file.\n"); } }

Rule: Always check for NULL after fopen() and always call fclose() when finished with a file.