C 低级 I/O : Why does it hang in the while loop?

标签 c posix low-level low-level-io

我第一次学习 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/

相关文章:

c - 随机数创建

c - 这个错误在 C : free(): invalid next size (fast): 0x00000000020b0200 中意味着什么

c - 从 C 中的命令行复数化字符串

c++ - 表访问性能

c++ - 使用 pthread_cond_broadcast 并行执行?

python - 最接近 Python 语法的语言是更底层的语言!

c - 如何修改返回值?

c - 如何写一个类似sftp的密码提示?

c - 访问共享内存中的结构后出现段错误?

.net - 我在哪里可以找到 CorFlags 值的每一位含义的引用?