C•File Handling
C File I/O: fopen, fread, fwrite, and fclose
Learn C file management from <stdio.h>, checking for NULL handles, buffered I/O, and closing streams.
Syntax
FILE* f = fopen("filename.txt", "w");
fclose(f);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| fopen | Function | Opens a file stream in specified mode ("r", "w", "a", "rb"). |
| fclose | Function | Flushes buffer and closes file descriptor. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C locally:
#include <stdio.h>
int main(void) {
// In-memory file stream simulation using tmpfile()
FILE* tempFile = tmpfile();
if (tempFile == NULL) {
printf("Failed to create stream!\n");
return 1;
}
// Write formatted lines to stream
fprintf(tempFile, "LOG: 2026-10-18 Server Initialized\n");
fprintf(tempFile, "LOG: 2026-10-18 Health Check OK\n");
// Rewind pointer back to beginning
rewind(tempFile);
// Read back line by line
printf("--- Reading from File Stream ---\n");
char line[128];
while (fgets(line, sizeof(line), tempFile) != NULL) {
printf("Read: %s", line);
}
fclose(tempFile);
printf("Stream closed successfully.\n");
return 0;
}Expected Output:
--- Reading from File Stream --- Read: LOG: 2026-10-18 Server Initialized Read: LOG: 2026-10-18 Health Check OK Stream closed successfully.
How It Works: Step-by-Step
- Lines 5-11: Creates temporary file stream and checks for NULL.
- Lines 13-15: fprintf writes text into stream buffer.
- Line 18: rewind(tempFile) resets file pointer back to byte 0.
- Lines 22-25: fgets reads lines until EOF (NULL).
Key Concepts
- Always verify that fopen() returned a non-NULL pointer before writing.
- fclose() flushes the stream buffer to disk and releases file descriptors.
Common Mistake: Forgetting to close open file handles with fclose()
Leaving file descriptors open exhausts OS file handle limits in long-running servers.
❌ Incorrect
FILE* f = fopen("log.txt", "w");
// Missing fclose(f) leaks OS descriptor!✅ Correct
FILE* f = fopen("log.txt", "w");
fclose(f);Related C Tutorials & Compiler
C Strings: Null-Terminated Character Arrays (char[])
Master null-terminated strings (\0), strlen, strcpy, strcat, and strcmp from string.h.
C Error Handling: Return Codes, errno, and perror
Handle system call failures in C using return codes, errno, and perror().
C Dynamic Memory: malloc, calloc, realloc, and free
Allocate heap memory dynamically at runtime using malloc, calloc, realloc, and free.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.