File I/O — fopen, fread, fwrite, fprintf, Binary vs Text
555 words
3 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# File I/O — fopen, fread, fwrite, fprintf, Binary vs Text ## 🎯 Learning Objectives - Open, read, write, and close files - Use formatted I/O (fprintf, fscanf) - Read/write binary data structures - Handle file I/O errors properly * * * ## 1. File Operations ### 1.1 Opening and Closing Files ### 1.2 File Modes Mode M...

File I/O — fopen, fread, fwrite, fprintf, Binary vs Text
🎯 Learning Objectives
- Open, read, write, and close files
- Use formatted I/O (fprintf, fscanf)
- Read/write binary data structures
- Handle file I/O errors properly
1. File Operations
1.1 Opening and Closing Files
cFILE *fp = fopen("data.txt", "r"); // Open for reading if (fp == NULL) { perror("Failed to open file"); return -1; } // Process file... fclose(fp); // Always close!
1.2 File Modes
| Mode | Meaning | File Exists | File Doesn't Exist |
|---|---|---|---|
| "r" | Read text | Open | Error (returns NULL) |
| "w" | Write text | Overwrite | Create new |
| "a" | Append text | Append to end | Create new |
| "r+" | Read/Write | Open (no truncate) | Error |
| "w+" | Read/Write | Overwrite | Create new |
| "a+" | Read/Append | Read + Append | Create new |
| "rb" | Read binary | Same as "r" | Same as "r" |
| "wb" | Write binary | Same as "w" | Same as "w" |
2. Text I/O
2.1 fprintf and fscanf
c// Writing FILE *out = fopen("output.txt", "w"); fprintf(out, "Name: %s, Age: %d, GPA: %.2f\n", "Alice", 22, 3.75); fclose(out); // Reading FILE *in = fopen("output.txt", "r"); char name[50]; int age; float gpa; fscanf(in, "Name: %s, Age: %d, GPA: %f", name, &age, &gpa); fclose(in);
2.2 fgets and fputs
cchar buffer[256]; // Read a line if (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("Read: %s", buffer); } // Write a string fputs("Hello, World!\n", fp);
3. Binary I/O
3.1 fread and fwrite
ctypedef struct { int id; char name[50]; double salary; } Employee; // Write binary Employee emp = {1, "Alice", 75000.0}; fwrite(&emp, sizeof(Employee), 1, fp); // Read binary Employee emp_read; fread(&emp_read, sizeof(Employee), 1, fp_type");
3.2 Binary vs Text
| Aspect | Text | Binary |
|---|---|---|
| Readability | Human-readable | Machine-only |
| Size | Larger (digits) | Compact |
| Portability | Newline issues | Platform-specific |
| Precision | Rounding in floats | Exact representation |
4. 📝 Practice Questions
Q1: What happens if you fopen a non-existent file with mode "r"?Answer: fopen returns NULL. Always check the return value before using the FILE pointer. errno is set to ENOENT (or similar) and perror can report the error. Q2: Write a program that copies one file to another.cvoid copy_file(const char *src, const char *dst) { FILE *in = fopen(src, "rb"); FILE *out = fopen(dst, "wb"); if (!in || !out) { perror("Error"); return; } char buffer[4096]; size_t bytes; while ((bytes = fread(buffer, 1, sizeof(buffer), in)) > 0) { fwrite(buffer, 1, bytes, out); } fclose(in); fclose(out); }Q3: Why should you always close a file after using it?Answer: To flush any buffered data to disk, release system resources (file descriptors are limited), and prevent data loss. The OS will close files when the program exits, but it's poor practice to rely on this. Q4: What is the difference between fgets and gets?Answer: fgets takes a size parameter (maximum characters to read), preventing buffer overflow. gets has NO size check and will overflow any buffer. gets was removed from the C11 standard. Q5: When would you use binary mode instead of text mode?Answer: When reading/writing structured data (C structs, arrays of numbers), binary data (images, executables), or when exact byte representation matters. Binary avoids conversion overhead and precision loss.
5. 🔗 Cross-References
- Week 5 - Dynamic Memory: Reading dynamic data from files
- BSCS4022 (OS): File descriptors, system calls (open, read, write) Join Discord PreviousStructures & UnionsNextPreprocessor