Week 8 · File Systems & File I/O
第 8 周 · 文件系统与文件I/O
Unix File Systems & C File Operations
Unix文件系统与C文件操作
File I/O, binary handling, directory operations, and permissions aligned with exam standards
文件I/O、二进制处理、目录操作与权限管理,对齐考试标准
🎯 Learning Objectives学习目标
- Master file I/O operations using
fopen, fprintf, fgetc, and fputc for text and binary files.掌握使用 fopen、fprintf、fgetc 和 fputc 进行文本和二进制文件的I/O操作。
- Understand Unix file system structure, pathnames, and directory traversal techniques.理解Unix文件系统结构、路径名和目录遍历技术。
- Implement file permission analysis using
stat() and interpret file metadata.使用 stat() 实现文件权限分析并解释文件元数据。
- Handle byte-level file operations including endianness and binary format parsing.处理字节级文件操作,包括字节序和二进制格式解析。
- Debug file I/O errors and implement robust error handling for exam scenarios.调试文件I/O错误并为考试场景实现健壮的错误处理。
🧭 Exam Alignment考试对齐
- File I/O operations — 22T2 Q7 & 22T3 Q6 require directory traversal and file processing skills.文件I/O操作 — 22T2 Q7 与 22T3 Q6 要求掌握目录遍历和文件处理技能。
- Binary file handling — Lab08 exercises directly map to exam questions on byte manipulation.二进制文件处理 — Lab08 练习直接对应考试中的字节操作题目。
- File permissions — Tutorial08
stat() questions appear in finals requiring permission analysis.文件权限 — Tutorial08 中的 stat() 题目在期末考试中要求权限分析。
- Error handling — All lab exercises emphasize
fopen() failure handling and NULL checks.错误处理 — 所有实验练习都强调 fopen() 失败处理和NULL检查。
- File format parsing — Lab08 "LIT file" format maps to exam custom format questions.文件格式解析 — Lab08 "LIT文件"格式对应考试中的自定义格式题目。
Coverage goals: implement ≥5 file I/O patterns, master ≥3 binary handling techniques, and document ≥2 directory operation templates for revision.
覆盖目标:实现 ≥5 种文件I/O模式,掌握 ≥3 种二进制处理技术,并记录 ≥2 个目录操作模板以便复习。
📚 Core Concepts核心概念
File I/O Operations文件I/O操作
fopen() opens files with modes like "r", "w", "a", "rb", "wb". Always check for NULL return. fclose() must be called to flush buffers and release resources.fopen() 以"r"、"w"、"a"、"rb"、"wb"等模式打开文件。必须检查NULL返回值。fclose() 必须调用以刷新缓冲区并释放资源。
Key functions: fprintf() for formatted output, fgetc()/fputc() for character I/O, fread()/fwrite() for binary data.关键函数:fprintf() 用于格式化输出,fgetc()/fputc() 用于字符I/O,fread()/fwrite() 用于二进制数据。
Unix File System StructureUnix文件系统结构
Tree structure with root directory "/". Absolute paths start with "/", relative paths don't. Special directories: "." (current), ".." (parent).以根目录"/"为起点的树形结构。绝对路径以"/"开头,相对路径不以"/"开头。特殊目录:"."(当前),".."(父目录)。
Pathnames can contain symbolic links creating graph structures. Directory traversal requires opendir(), readdir(), closedir().路径名可能包含符号链接形成图形结构。目录遍历需要 opendir()、readdir()、closedir()。
File Permissions & Metadata文件权限与元数据
stat() provides file metadata including permissions, size, timestamps. Permission bits: user/group/other × read/write/execute (rwx).stat() 提供文件元数据,包括权限、大小、时间戳。权限位:用户/组/其他 × 读/写/执行(rwx)。
Use S_ISREG(), S_ISDIR() macros to check file types. Extract permission bits with bitwise operations on st_mode.使用 S_ISREG()、S_ISDIR() 宏检查文件类型。用位运算从 st_mode 提取权限位。
Binary File Handling二进制文件处理
Open with "rb"/"wb" modes. Read/write raw bytes using fgetc()/fputc(). Handle endianness when reading multi-byte integers.以"rb"/"wb"模式打开。使用 fgetc()/fputc() 读写原始字节。读取多字节整数时处理字节序。
Use fseek() for random access. Check isprint() to determine character printability for hex dumps.使用 fseek() 进行随机访问。检查 isprint() 判断字符在十六进制转储中的可打印性。
Error Handling Patterns错误处理模式
Always check fopen() for NULL. Use perror() for system error messages. Check return values of I/O functions for EOF or error conditions.总是检查 fopen() 的NULL返回值。使用 perror() 输出系统错误消息。检查I/O函数的返回值以处理EOF或错误条件。
Common errors: file not found, permission denied, disk full. Implement graceful failure with cleanup and informative messages.常见错误:文件未找到、权限拒绝、磁盘已满。实现优雅失败,包含清理和信息提示。
File Positioning & Seeking文件定位与寻址
fseek() moves file position with SEEK_SET, SEEK_CUR, SEEK_END. ftell() returns current position. Essential for binary file parsing.fseek() 使用SEEK_SET、SEEK_CUR、SEEK_END移动文件位置。ftell() 返回当前位置。这对二进制文件解析至关重要。
Handle large files beyond INT_MAX using long positions. Random access enables efficient algorithms without reading entire files.使用 long 位置处理超过INT_MAX的大文件。随机访问可以高效实现算法而无需读取整个文件。
🧪 Worked Examples示例串讲
Example 1 — Binary File Creation and Reading示例 1 — 二进制文件创建与读取
Create a binary file with specific byte values, then read and display in hex format. Handle byte range validation (0-255).创建包含特定字节值的二进制文件,然后读取并以十六进制格式显示。处理字节范围验证(0-255)。
// Create binary file
FILE *fp = fopen("data.bin", "wb");
if (fp == NULL) {
perror("fopen");
return 1;
}
for (int i = 0; i < argc-1; i++) {
int byte = atoi(argv[i+1]);
if (byte < 0 || byte > 255) {
fprintf(stderr, "Invalid byte: %d\n", byte);
return 1;
}
fputc(byte, fp);
}
fclose(fp);
Always validate input ranges and check fopen() for NULL. Close files to ensure data is written.
总是验证输入范围并检查fopen()的NULL返回值。关闭文件以确保数据被写入。
Example 2 — File Permission Analysis示例 2 — 文件权限分析
Use stat() to extract file permissions and display in standard format. Handle both files and directories.使用 stat() 提取文件权限并以标准格式显示。处理文件和目录。
struct stat sb;
if (stat(filename, &sb) != 0) {
perror("stat");
return 1;
}
// Check file type
if (S_ISREG(sb.st_mode)) printf("-");
else if (S_ISDIR(sb.st_mode)) printf("d");
// Extract permissions
mode_t mode = sb.st_mode;
printf("%c", (mode & S_IRUSR) ? 'r' : '-');
printf("%c", (mode & S_IWUSR) ? 'w' : '-');
printf("%c", (mode & S_IXUSR) ? 'x' : '-');
// Repeat for group and other...
Maps directly to Lab08 "file_modes.c" and appears in exam questions requiring permission interpretation.直接对应Lab08的"file_modes.c",并出现在要求权限解释的考试题目中。
⚠️ Common Pitfalls易错点
- Forgetting to check
fopen() for NULL return leads to segmentation faults.忘记检查 fopen() 的NULL返回值会导致段错误。
- Not closing files causes buffer issues and resource leaks in long-running programs.不关闭文件会在长时间运行的程序中导致缓冲区问题和资源泄漏。
- Using text mode ("r"/"w") for binary data corrupts newline characters on some systems.对二进制数据使用文本模式("r"/"w")会在某些系统上破坏换行符。
- Ignoring
fseek() return value can lead to incorrect file positioning in large files.忽略 fseek() 返回值可能在大文件中导致错误的文件定位。
- Mixing byte values outside 0-255 range when creating binary files causes undefined behavior.创建二进制文件时使用0-255范围外的字节值会导致未定义行为。
🛠️ Practice Task实践任务
Implement file_analyzer.c: analyze any file and report statistics including size, file type, permissions, and hex dump of first 256 bytes with ASCII representation.实现 file_analyzer.c:分析任何文件并报告统计信息,包括大小、文件类型、权限以及前256字节的十六进制转储和ASCII表示。
- Use
stat() for metadata extraction and file type detection.使用 stat() 进行元数据提取和文件类型检测。
- Implement hex dump with 16 bytes per line, showing both hex and printable ASCII.实现每行16字节的十六进制转储,同时显示十六进制和可打印ASCII。
- Handle both text and binary files gracefully with appropriate error messages.优雅地处理文本和二进制文件,提供适当的错误消息。
- Optional Optional: add directory traversal to analyze all files in a given directory.可选 Optional:添加目录遍历以分析给定目录中的所有文件。
🧪 Tutorial & Lab Mapping教程与实验映射
Tutorial 08 HighlightsTutorial 08 精要
- Unix filesystem structure and pathname analysis exercises.Unix文件系统结构和路径名分析练习。
- File opening scenarios and error condition identification.文件打开场景和错误条件识别。
- Practical programming tasks: first_line.c, write_line.c, append_line.c.实际编程任务:first_line.c、write_line.c、append_line.c。
- Binary data limitations with fgets/fputs and character encoding.fgets/fputs处理二进制数据的限制和字符编码。
Lab 08 Programming TasksLab 08 编程任务
- create_integers_file.c — generate files with integer ranges.create_integers_file.c — 生成包含整数范围的文件。
- print_bytes.c — display byte-level file analysis.print_bytes.c — 显示字节级文件分析。
- create_binary_file.c — create custom binary files.create_binary_file.c — 创建自定义二进制文件。
- read_lit_file.c — parse custom LIT file format.read_lit_file.c — 解析自定义LIT文件格式。
- file_modes.c — analyze and display file permissions.file_modes.c — 分析并显示文件权限。
📝 Study Log学习记录
- Inputs shared: files.pdf, Lab08 specification, Tutorial08 handout, exam 22T2 Q7 + 22T3 Q6 file operations.提供资料:files.pdf、Lab08 说明、Tutorial08 讲义、22T2 Q7 与 22T3 Q6 文件操作题。
- Prompt: "Create file I/O templates aligned with lab autograder and explain Unix filesystem behavior."提示词:"创建与实验自动评测对齐的文件I/O模板,并解释Unix文件系统行为。"
- Breakthrough: Understanding binary vs text mode differences prevented data corruption in LIT file parsing.收获: 理解二进制与文本模式差异避免了LIT文件解析中的数据损坏。
- Misconception fixed: Previously forgot NULL checks for fopen() — now systematically verify all file operations.修正误区: 过去忘记检查fopen()的NULL返回值,现在系统性验证所有文件操作。
- Action items: Practice stat() bit manipulation; rehearse directory traversal with opendir/readdir for exam scenarios.后续行动: 练习stat()位操作;为考试场景练习使用opendir/readdir的目录遍历。
Premium Quiz — 40 Questions on File SystemsPremium 测验 — 40 道文件系统题
28 basic (file I/O, permissions) · 8 intermediate (binary handling) · 4 advanced (directory traversal & error handling)基础28题(文件I/O与权限)· 中级8题(二进制处理)· 高级4题(目录遍历与错误处理)
🔒
Open Week 8 Quiz (Premium)
打开第 8 周测验(会员)
🔭 Next Week Preview下周预告
Week 9 advances to complex file handling: UTF-8 validation, environment variables, advanced permissions, and file seeking. Preview lab09 exercises and prepare for metadata manipulation.第 9 周将深入复杂文件处理:UTF-8验证、环境变量、高级权限和文件寻址。请预习lab09练习并准备元数据操作。
📎 Resources & Checklist资源与检查表
- PPT: files.pdf p1–35 (file I/O & Unix filesystem).PPT:files.pdf 第 1–35 页(文件I/O与Unix文件系统)。
- Autotest:
1521 autotest lab08_create_integers_file, lab08_print_bytes, lab08_create_binary_file, lab08_file_modes.自动测试:1521 autotest lab08_create_integers_file、lab08_print_bytes、lab08_create_binary_file、lab08_file_modes。
- Self-check: Can you handle NULL returns from fopen()? Can you extract file permissions from stat() results?自检:能否处理fopen()的NULL返回值?能否从stat()结果中提取文件权限?