← Back to C Course | Chapter 10: File I/O | Lesson 2 of 6

C fopen() & fclose()

fopen opens a file and fclose closes it, like opening and closing a notebook. The mode you choose says whether you will read, write, or add.
Syntax
c
FILE *file_pointer = fopen("filename.txt", "mode");  // "r", "w" or "a"

if (file_pointer == NULL) {
  // could not open the file
}

fclose(file_pointer);

Opening a file with fopen()

Common modes include "r" (read), "w" (write, truncating existing content), and "a" (append) -- always check the returned pointer against NULL before using it, since a missing file or insufficient permissions will cause fopen() to fail silently otherwise.

Example: Opening a file with fopen()

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp = fopen("data.txt", "w");
	// Check whether fp == NULL
	if (fp == NULL) {
		// Print formatted text to the screen
		printf("Failed to open");
		// Send 1 back to the caller
		return 1;
	}
	fprintf(fp, "Hello");
	fclose(fp);
	// Return 0 to signal that the program finished successfully
	return 0;
}

Closing a file with fclose()

Beyond just flushing buffered writes, forgetting to close files can eventually exhaust the operating system's limit on how many files a single process can have open simultaneously, causing later fopen() calls to start failing.

Example: Closing a file with fclose()

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "Hello");
	fclose(fp);
	// Print formatted text to the screen
	printf("Closed properly");
	// Return 0 to signal that the program finished successfully
	return 0;
}

Reading modes ("r", "rb")

Text mode (r) may perform platform-specific newline translation (like converting \r\n to \n on Windows), which corrupts binary data such as images -- binary mode (rb) disables this translation and reads bytes exactly as stored.

Example: Reading modes ("r", "rb")

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "Hello");
	fclose(fp);
	fp = fopen("data.txt", "r");
	char buffer[10];
	fgets(buffer, 10, fp);
	// Print formatted text to the screen
	printf("%s", buffer);
	fclose(fp);
	// Return 0 to signal that the program finished successfully
	return 0;
}

Writing modes ("w", "wb", "a")

w mode silently destroys any existing file content the moment you open it, even before you write anything -- if you need to preserve existing data while adding to it, a mode is the safer choice.

Example: Writing modes ("w", "wb", "a")

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "First");
	fclose(fp);
	fp = fopen("data.txt", "a");
	fprintf(fp, "Second");
	fclose(fp);
	// Print formatted text to the screen
	printf("Appended without erasing");
	// Return 0 to signal that the program finished successfully
	return 0;
}

Managing multiple open files

Each FILE pointer independently tracks its own read/write position within its file, so operations on one open file have no effect on another -- just make sure every fopen() call you make has a corresponding fclose() eventually.

Example: Managing multiple open files

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp1 = fopen("a.txt", "w");
	FILE *fp2 = fopen("b.txt", "w");
	fprintf(fp1, "File A");
	fprintf(fp2, "File B");
	fclose(fp1);
	fclose(fp2);
	// Print formatted text to the screen
	printf("Both files written independently");
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking whether fopen returned NULL before using the file pointer.
  2. Opening an existing file with mode "w", which erases its previous content; use "a" to append.
  3. Forgetting fclose, so buffered output may never reach the disk.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.