C Low level I/O : 为什么会在while循环中挂起?

C Low level I/O : Why does it hang in the while loop?

我第一次在 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 在调用 returns -1.