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

Tom*_*uie -4 c io

int fd, read_byte;
char *c;  

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

read_byte = read(fd, c, 20);

printf("");
Run Code Online (Sandbox Code Playgroud)

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

HAL*_*HAL 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; 
}
Run Code Online (Sandbox Code Playgroud)

  • +1我没注意到他用open代替了fopen! (2认同)