【问题标题】:C Low level I/O : Why does it hang in the while loop?C Low level I/O : 为什么它会挂在 while 循环中?
【发布时间】: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


【解决方案1】:

调用read(fd, buf, 1),如果成功,将读取一个字节的数据,然后将文件指针向前移动一个字节!然后调用lseek(fd, -1, SEEK_CUR) 会将文件指针向后 移动一个字节!

最终结果:您的 while 循环将继续读取 same 字节!

解决方案:在您的 while 循环内,使用以下命令设置文件指针以读取前一个字节:lseek(fd, -2, SEEK_CUR) - 和 break 在该调用返回 -1 时退出循环。

【讨论】:

猜你喜欢
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 2011-06-14
  • 2015-11-29
相关资源
最近更新 更多