【问题标题】:Read last 20 bytes from a file从文件中读取最后 20 个字节
【发布时间】:2013-12-10 14:36:48
【问题描述】:
int fd, read_byte;
char *c;  

fd = open("foo.txt", O_RDONLY);

read_byte = read(fd, c, 20);

printf("");

如何从文件中读取最后 20 个字节并将 read_byte 打印到屏幕上。

【问题讨论】:

  • 为什么open而不是fopen?

标签: c io


【解决方案1】:

使用lseek(2)

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main()
{
    int fd, read_byte;
    char c[21];

    fd = open("foo.txt", O_RDONLY);
    if (fd == -1) {
        printf("Error opening file\n");
        return -1;
    }

    // reposition fd to position `-20` from the end of file.
    lseek(fd, -20L, SEEK_END);  
    read_byte = read(fd, c, 20); // Read 20 bytes
    c[read_byte] = '\0';

    printf("%s\n", c);

    close(fd);

    return 0; 
}

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多