Deleting Lines from Files - Complete Guide 删除文件行 - 完整指南
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开始计数。
| 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") |
| 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 清空内容 |
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. 解决方案:始终使用临时文件:从原文件读取 → 写入临时文件 → 替换原文件。
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)
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),如果为真则删除临时文件。
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++
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. 不能安全地同时读写同一文件。 解决方案是从原文件读取,将修改后的内容写入临时文件, 然后用临时文件替换原文件。
Ready to practice? Take the Day 1 Final Review Quiz covering all File I/O concepts! 准备好练习了吗?参加 Day 1 期末复习测验,涵盖所有文件 I/O 概念!
✨ First 10 questions FREE for all users | Questions 11-30 require Premium ✨ 前10题对所有用户免费 | 第11-30题需要 Premium 会员
Start Day 1 Quiz → 开始 Day 1 测验 →