-4
int fd, read_byte;
char *c;
fd = open("foo.txt", O_RDONLY);
read_byte = read(fd, c, 20);
printf("");
如何從文件中讀取最後20個字節並將read_byte打印到屏幕。從文件中讀取最後20個字節
int fd, read_byte;
char *c;
fd = open("foo.txt", O_RDONLY);
read_byte = read(fd, c, 20);
printf("");
如何從文件中讀取最後20個字節並將read_byte打印到屏幕。從文件中讀取最後20個字節
使用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;
}
+1我沒有注意到他用開放而不是fopen! –
爲什麼開不的fopen? – Marco