[英]How to read the last n characters of a txt file, without using stdio.h?
我试图从文本文件中读取最后的n位数字而不使用stdio.h函数调用。 我不确定如何做到这一点因为我不使用fseek而不使用stdio.h并且我不熟悉系统调用。 任何帮助,将不胜感激。
#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);
}
你可以使用lseek
。 这是原型:
off_t lseek(int fd, off_t offset, int whence);
以下是将其集成到代码中的方法:
lseek(fd, -200, SEEK_END);
read(fd, buf, 200);
只是为了变化:
struct stat sb;
int fd = open( filename, O_RDONLY );
fstat( fd, &sb );
pread( fd, buf, 200, sb.st_size - 200 );
请注意, lseek()
然后read()
不是原子的,因此如果多个线程正在访问文件描述符,那么您将遇到竞争条件。 pread()
是原子的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.