从文件中读取最后20个字节

时间:2013-12-10 14:36:49

标签: c io

int fd, read_byte;
char *c;  

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

read_byte = read(fd, c, 20);

printf("");

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

1 个答案:

答案 0 :(得分:5)

使用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; 
}