我第一次学习 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)
,如果成功,将读取一个字节的数据,然后将文件指针向前移动一个字节!来电lseek(fd, -1, SEEK_CUR)
然后会将文件指针向后移动一个字节!
最终结果:您的while
循环将永远继续读取相同字节!
解决方案:在您的 while
内循环使用以下命令设置文件指针以读取前一个字节:lseek(fd, -2, SEEK_CUR)
- 和break
当该调用返回 -1
时退出循环.
关于C 低级 I/O : Why does it hang in the while loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59344167/