Linux 文件 IO 删除文件的第10行,使用read,write,open,close,lseek,要求具体代码
时间: 2024-05-07 18:15:18 浏览: 12
下面是一个示例代码,可以删除文件的第10行。假设文件名为test.txt。
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main()
{
int fd = open("test.txt", O_RDWR);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
int n;
int line = 1;
int offset = 0;
int found = 0;
while ((n = read(fd, buf, BUF_SIZE)) > 0) {
for (int i = 0; i < n; i++) {
if (line == 10) {
found = 1;
}
if (buf[i] == '\n') {
line++;
}
if (!found) {
offset++;
}
}
if (found) {
offset -= (n - i);
break;
}
}
if (lseek(fd, offset, SEEK_SET) == -1) {
perror("lseek");
exit(EXIT_FAILURE);
}
int m = 0;
while ((n = read(fd, buf, BUF_SIZE)) > 0) {
if (write(fd, buf, n) != n) {
perror("write");
exit(EXIT_FAILURE);
}
m += n;
}
if (ftruncate(fd, m) == -1) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}
```
这个代码的大致思路是,首先读取文件,找到第10行的开始位置(即第9行结束的位置),然后使用lseek设置文件指针到这个位置,接着读取剩余的内容,并将其写回到文件中。最后使用ftruncate截断文件,使文件大小减少相应的字节数。
需要注意的是,这个代码没有做过多的错误处理,实际使用时需要根据具体情况进行适当的改进。