【问题标题】:How to read the last n characters of a txt file, without using stdio.h?如何在不使用 stdio.h 的情况下读取 txt 文件的最后 n 个字符?
【发布时间】:2019-08-26 18:35:10
【问题描述】:

我试图在不使用 stdio.h 函数调用的情况下从文本文件中读取最后 n 个数字。我不确定如何执行此操作,因为我无法在不使用 stdio.h 的情况下使用 fseek 并且我不熟悉系统调用。任何帮助将不胜感激。


#include <unistd.h>

#include <sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>

int main() {

    int fd;
    char buf[200];

    fd = open("logfile.txt", O_RDONLY);
    if (fd == -1){
        fprintf(stderr, "Couldn't open the file.\n");
        exit(1); }

    read(fd, buf, 200);

    close(fd);
}

【问题讨论】:

  • 你能解释一下为什么你不能使用stdio.h吗?
  • 看来你要使用的是lseek
  • 如果我看到错误信息Couldn't open the file.,我马上问了2个问题。哪个文件?为什么不?您的错误消息应包含这两个详细信息。使用perror("logfile.txt") 很容易做到这一点。可以提出的第三个问题是“哪个程序?”一些系统也为此提供了简单的包装器,例如err(EXIT_FAILURE, "logfile.txt")
  • @dedecos 这是一个家庭作业,教我们系统调用
  • 不相关的问题:你运行的是什么操作系统(如果是 Linux,是什么发行版)?

标签: c system-calls


【解决方案1】:

您可以使用lseek。这是原型:

off_t lseek(int fd, off_t offset, int whence);

您可以通过以下方式将其集成到您的代码中:

lseek(fd, -200, SEEK_END);
read(fd, buf, 200);

【讨论】:

    【解决方案2】:

    只为多样化:

    struct stat sb;
    
    int fd = open( filename, O_RDONLY );
    fstat( fd, &sb );
    pread( fd, buf, 200, sb.st_size - 200 );
    

    注意lseek() 然后read() 不是原子的,所以如果有多个线程访问文件描述符,就会出现竞争条件。 pread() 是原子的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多