【发布时间】:2019-12-15 13:05:14
【问题描述】:
我第一次学习 C 中的低级 I/O,我正在尝试编写一个向后打印文件的程序,但是这个 while 循环似乎不起作用。为什么会这样?
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFSIZE 4096
int main(){
int n;
int buf[BUFFSIZE];
off_t currpos;
int fd;
if((fd = open("fileprova", O_RDWR)) < 0)
perror("open error");
if(lseek(fd, -1, SEEK_END) == -1)
perror("seek error");
while((n = read(fd, buf, 1)) > 0){
if(write(STDOUT_FILENO, buf, n) != n)
perror("write error");
if(lseek(fd, -1, SEEK_CUR) == -1)
perror("seek error");
currpos = lseek(fd, 0, SEEK_CUR);
printf("Current pos: %ld\n", currpos);
}
if(n < 0)
perror("read error");
return 0;
}
【问题讨论】:
-
C 和 C++ 是不同的语言。选一个。您的示例未使用任何 C++,因此我删除了该标记。
-
Read 使指针前进 1,因此 seek -1 将始终读取相同的字符。
-
你需要从end-1开始减去2
-
@stark 哦,好的,太好了,谢谢!
-
顺便说一句,将
pread读入或char buf[4096]4k 块左右的数组会更有效,用循环将其反转,然后写出来。因此,您的系统调用减少了 2^10 倍,并且运行速度要快得多。 (每个字节进行 1 次系统调用是非常低效的。)
标签: c posix low-level low-level-io