linux 文件读写指定位置内容
时间: 2023-10-14 11:28:48 浏览: 43
可以使用lseek函数在文件中定位到指定位置,然后使用read或write函数进行读写操作。
示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDWR);
if (fd < 0) {
perror("open");
exit(1);
}
// 定位到文件末尾
off_t end_offset = lseek(fd, 0, SEEK_END);
if (end_offset < 0) {
perror("lseek");
exit(1);
}
// 定位到文件中间
off_t mid_offset = lseek(fd, end_offset / 2, SEEK_SET);
if (mid_offset < 0) {
perror("lseek");
exit(1);
}
// 读取中间位置的内容
char buf[1024];
ssize_t nread = read(fd, buf, sizeof(buf));
if (nread < 0) {
perror("read");
exit(1);
}
printf("Read %zd bytes: %.*s\n", nread, (int)nread, buf);
// 写入新的内容到中间位置
const char* new_content = "new content";
ssize_t nwrite = write(fd, new_content, strlen(new_content));
if (nwrite < 0) {
perror("write");
exit(1);
}
printf("Write %zd bytes: %s\n", nwrite, new_content);
close(fd);
return 0;
}
```
该示例程序首先打开文件test.txt,然后将文件指针定位到文件末尾和文件中间位置,分别进行读取和写入操作。最后关闭文件描述符。