Back to Final Review Hub 返回期末复习中心
Day 1 - Final Review Day 1 - 期末复习

📁 File I/O Operations 📁 文件 I/O 操作

Deleting Lines from Files - Complete Guide 删除文件行 - 完整指南

📝 Problem Statement 📝 题目描述

Task: Write a C program that takes two arguments (filename and line number n), and deletes the n-th line from the file. Lines are numbered starting at 1. 任务:编写一个C程序,接收两个参数(文件名和行号n), 从文件中删除第n行。行号从1开始计数。

# Example Usage# 使用示例 printf 'Hello\nhow\nare\nyou\n' > hello.txt cat hello.txt Hello how are you ./22t3final_q6 hello.txt 3 cat hello.txt Hello how you
⚠️ Key Requirements: ⚠️ 关键要求:
  • Use a temporary file (cannot read and write to the same file simultaneously) 使用临时文件(不能同时读写同一文件)
  • No output to stdout or stderr 不输出到 stdout 或 stderr
  • If file has fewer than n lines, do nothing 如果文件行数少于n,则不做任何操作
  • No error checking required 不需要错误检查

✅ Complete Solution ✅ 完整答案

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char *filename = argv[1]; int n = atoi(argv[2]); FILE *input = fopen(filename, "r"); FILE *output = fopen("temp_file.txt", "w"); char line[10000]; int line_number = 0; while (fgets(line, sizeof(line), input) != NULL) { line_number++; if (line_number != n) { fputs(line, output); } } fclose(input); fclose(output); if (line_number < n) { remove("temp_file.txt"); return 0; } remove(filename); rename("temp_file.txt", filename); return 0; }

🔄 Process Flow Diagram 🔄 处理流程图

1️⃣ Get filename and line number from command-line arguments 1️⃣ 从命令行参数获取文件名和行号
2️⃣ Open original file for reading (fopen with "r" mode) 2️⃣ 打开原文件进行读取(fopen 使用 "r" 模式)
3️⃣ Create temporary file (fopen with "w" mode) 3️⃣ 创建临时文件(fopen 使用 "w" 模式)
4️⃣ Read lines one by one, skip line n, write others to temp file 4️⃣ 逐行读取,跳过第n行,其他行写入临时文件
5️⃣ Close both files 5️⃣ 关闭两个文件
6️⃣ Check if file had enough lines 6️⃣ 检查文件是否有足够的行数
7️⃣ Replace original file with temp file (remove + rename) 7️⃣ 用临时文件替换原文件(remove + rename)

🔧 Essential Functions Reference 🔧 核心函数参考

Function函数 Purpose用途 Example示例
fopen() Open file, returns FILE* 打开文件,返回 FILE* fopen("file.txt", "r")
fclose() Close file 关闭文件 fclose(file)
fgets() Read one line (includes \n) 读取一行(包含 \n) fgets(buf, size, file)
fputs() Write string to file 写入字符串到文件 fputs(str, file)
remove() Delete file 删除文件 remove("file.txt")
rename() Rename/move file 重命名/移动文件 rename("old", "new")
atoi() String to integer 字符串转整数 atoi("123")

📂 File Opening Modes 📂 文件打开模式

Mode模式 Meaning含义 File Doesn't Exist文件不存在 File Exists文件存在
"r" Read 读取 Error 错误 Open file 打开文件
"w" Write 写入 Create new 创建新文件 Clear content 清空内容
"a" Append 追加 Create new 创建新文件 Append to end 追加到末尾
"r+" Read+Write 读写 Error 错误 Open file 打开文件
"w+" Write+Read 写读 Create new 创建新文件 Clear content 清空内容

⚠️ Common Mistakes to Avoid ⚠️ 常见错误

❌ Mistake 1: Not Using Temporary File ❌ 错误1:不使用临时文件

Problem: Trying to read and write to the same file simultaneously causes data corruption. 问题:尝试同时读写同一文件会导致数据损坏。

Solution: Always use a temporary file: read from original → write to temp → replace original. 解决方案:始终使用临时文件:从原文件读取 → 写入临时文件 → 替换原文件。

❌ Mistake 2: Wrong File Replacement Order ❌ 错误2:文件替换顺序错误

Problem: Calling rename() before remove() causes errors. 问题:在 remove() 之前调用 rename() 会导致错误。

Correct Order: 1) remove(filename) → 2) rename(temp_filename, filename) 正确顺序:1) remove(filename) → 2) rename(temp_filename, filename)

❌ Mistake 3: Forgetting to Check Line Count ❌ 错误3:忘记检查行数

Problem: If file has fewer than n lines, should do nothing (not replace file). 问题:如果文件行数少于n,应该什么都不做(不替换文件)。

Solution: Check if (line_number < n) and remove temp file if true. 解决方案:检查 if (line_number < n),如果为真则删除临时文件。

❌ Mistake 4: Line Numbering Confusion ❌ 错误4:行号计数混淆

Problem: Lines start at 1 (not 0), but counter starts at 0. 问题:行号从1开始(不是0),但计数器从0开始。

Solution: Initialize line_number = 0, increment at start of loop: line_number++ 解决方案:初始化 line_number = 0,在循环开始时递增:line_number++

💡 Key Concepts Summary 💡 核心概念总结

🔑 Why Use Temporary Files? 🔑 为什么使用临时文件?

You cannot safely read from and write to the same file simultaneously. The solution is to read from the original file, write modified content to a temporary file, then replace the original with the temporary file. 不能安全地同时读写同一文件。 解决方案是从原文件读取,将修改后的内容写入临时文件, 然后用临时文件替换原文件。

🔑 File Modification Pattern 🔑 文件修改模式

// Standard pattern for modifying files// 修改文件的标准模式 1. fopen(filename, "r") // Open original for reading// 打开原文件读取 2. fopen("temp.txt", "w") // Create temp file for writing// 创建临时文件写入 3. while (fgets()) { ... } // Process line by line// 逐行处理 4. fclose() // Close both files// 关闭两个文件 5. remove() + rename() // Replace original// 替换原文件