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

C File Handling Introduction

Introduction to Files

This persistence is exactly why programs use files for anything that needs to survive a restart -- configuration settings, saved game progress, or logs are all stored this way rather than only living in the program's in-memory variables.

Example: Introduction to Files

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("notes.txt", "w");
	fprintf(fp, "Saved data");
	fclose(fp);
	printf("Data persisted to a file");
	return 0;
}

File Streams in C

The FILE pointer (returned by fopen()) is an opaque handle -- you never need to know its internal structure, only to pass it consistently to every file function (fread, fwrite, fclose, etc.) that operates on that particular open file.

Example: File Streams in C

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "Hello");
	fclose(fp);
	return 0;
}

Standard Streams vs Files

stdin, stdout, and stderr are actually already-open FILE pointers that your program receives automatically at startup, which is why functions like printf() (which writes to stdout) don't require you to open anything first.

Example: Standard Streams vs Files

c
#include <stdio.h>
int main() {
	printf("This goes to stdout automatically");
	return 0;
}

Basic File operations

Skipping the close step risks losing buffered data that hasn't been physically written to disk yet, since many I/O operations are buffered in memory for performance and only flushed to disk at certain points, including when the file closes.

Example: Basic File operations

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("log.txt", "w");
	fprintf(fp, "entry");
	fclose(fp);
	printf("Closed the file");
	return 0;
}

Checking file existence

This is a common lightweight pattern for existence checks, though it has a side effect: if the file does exist, you've now opened it and must remember to close it again, or you'll leak a file handle.

Example: Checking file existence

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("maybe.txt", "r");
	if (fp != NULL) {
		printf("File exists");
		fclose(fp);
	} else {
		printf("File does not exist");
	}
	return 0;
}
🔒

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.