导航:首页 > 操作系统 > lintlinux

lintlinux

发布时间:2024-02-03 17:48:05

linux c怎么实现从文件的最后一行一行向前读文件

下面的例子使用mmap读最后20行(假设最后20行不会超过1024字节)
/*-
* Copyright (C), 1988-2014, mymtom
*
* vi:set ts=4 sw=4:
*/
#ifndef lint
static const char rcsid[] = "$Id$";
#endif /* not lint */
/**
* @file last20.c
* @brief
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
char *memchrr(const void *v1, const char *v2, int c)
{
char *s1, *s2;
char *p;
s1 = (char *)v1;
s2 = (char *)v2;
for (p = s2; p >= s1; --p) {
if (*p == c)
return p;
}
return NULL;
}
#define READSIZE 1024
int main(int argc, char *argv[])
{
int ret;
FILE *fp;
char *addr;
size_t len;
int prot;
int flags;
int fd;
off_t off;
off_t rem;
long pagesize;
struct stat buf;
pagesize = sysconf(_SC_PAGESIZE);
fp = fopen("last20.c", "rb");
fd = fileno(fp);
ret = fstat(fd, &buf);
if (buf.st_size <= READSIZE || buf.st_size <= pagesize) {
off = 0;
len = buf.st_size;
} else {
off = buf.st_size - READSIZE;
rem = off % pagesize;
off = off - rem;
len = READSIZE + rem;
}
/*
printf("size=%d READSIZE=%d off=%d len=%d\n",
(int)buf.st_size, (int)READSIZE, (int)off, (int)len);
*/
prot = PROT_READ;
flags = MAP_PRIVATE;
addr = mmap(NULL, len, prot, flags, fd, off);
fclose(fp);
{
int i, n;
char *head, *tail;
size_t size;
char line[1024];
tail = addr + len - 1;
n = 20;
for (i = 0; i < n; ++i) {
head = memchrr(addr, tail - 1, '\n');
if (head == NULL) {
size = tail - addr;
memcpy(line, addr, size);
line[size] = '\0';
} else {
size = tail - head - 1;
memcpy(line, head + 1, size);
line[size] = '\0';
tail = head;
}
printf("%s\n", line);
if (head == NULL) {
break;
}
}
}
munmap(addr, len);
return 0;
}
运行结果为:
./last20 | tac | cat -n
line[size] = '\0';
} else {
size = tail - head - 1;
memcpy(line, head + 1, size);
line[size] = '\0';
tail = head;
}
printf("%s\n", line);
if (head == NULL) {
break;
}
}
}
munmap(addr, len);
return 0;
}

阅读全文

与lintlinux相关的资料

热点内容
怎么进入电脑板2b2t服务器 浏览:282
idea编译进度条 浏览:132
文件夹工具箱软件 浏览:686
最近为什么手机连不上索尼服务器 浏览:877
海康录像机怎么关视频加密 浏览:786
编程以后有可能被机器人代替吗 浏览:522
windows创建文件命令 浏览:986
linuxcopy文件内容 浏览:383
程序员帅哥秃顶 浏览:839
阿里云服务器开通流程 浏览:105
如何开云服务器 浏览:979
网站小说源码 浏览:302
php用什么ide 浏览:867
网上预约课程app哪个好 浏览:153
android兼容测试工具 浏览:97
云服务器不支持虚拟化怎么办 浏览:190
加密方式的演变 浏览:364
java常用算法pdf 浏览:735
服务器数据遇到异常什么原因 浏览:452
phpexif信息 浏览:544