C Example Code2026-03-252 min read
Master text and binary file I/O operations in C using fopen, fprintf, fscanf, fread, and fwrite with error handling and buffer flushing.
File Streams in Standard C
File input and output in C utilizes the standard FILE* stream handle from <stdio.h>. Always verify that fopen() returns a non-null pointer before attempting read/write operations.
C Source Code: Text & Binary File Operations
c (ISO Standard)#include <stdio.h> #include <stdlib.h> typedef struct { int id; char name[32]; double score; } StudentRecord; int main() { const char *filename = "students.dat"; /* 1. Write binary records to file */ FILE *outFile = fopen(filename, "wb"); if (!outFile) { perror("Failed to open file for writing"); return EXIT_FAILURE; } StudentRecord s1 = {101, "Alice Smith", 94.5}; StudentRecord s2 = {102, "Bob Johnson", 88.0}; fwrite(&s1, sizeof(StudentRecord), 1, outFile); fwrite(&s2, sizeof(StudentRecord), 1, outFile); fclose(outFile); printf("Binary records successfully written to %s.\n", filename); /* 2. Read binary records back from file */ FILE *inFile = fopen(filename, "rb"); if (!inFile) { perror("Failed to open file for reading"); return EXIT_FAILURE; } StudentRecord reader; printf("\nReading binary records from disk:\n"); while (fread(&reader, sizeof(StudentRecord), 1, inFile) == 1) { printf(" ID: %d | Name: %-12s | Score: %.1f\n", reader.id, reader.name, reader.score); } fclose(inFile); remove(filename); /* Clean up temporary file */ return EXIT_SUCCESS; }
Sample Output
text (ISO Standard)Binary records successfully written to students.dat. Reading binary records from disk: ID: 101 | Name: Alice Smith | Score: 94.5 ID: 102 | Name: Bob Johnson | Score: 88.0
Complexity Analysis
- Time Complexity: $O(filesize)$ bounded by disk I/O throughput.
- Space Complexity:
O(1)fixed memory struct buffer.
Related Guides
- Comprehensive tutorial in File Handling in C.
- Record modeling with structs in Structures in C.