我第一次学习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;
}
调用read(fd, buf, 1)
,如果成功,将读取一个字节的数据,然后将文件指针forward移一个字节!然后,调用lseek(fd, -1, SEEK_CUR)
将文件指针backward移一个字节!
最终结果:您的while
循环将永远永远读取same字节!
解决方案:在while
循环内,使用以下命令设置文件指针以读取前一个字节:lseek(fd, -2, SEEK_CUR)
-当该调用返回break
时,-1
不在循环中。