导航:首页 > 操作系统 > 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相关的资料

热点内容
毒app哪个耐克鉴定师好 浏览:740
化度寺碑pdf 浏览:320
导航安卓机如何下载腾讯视频 浏览:98
applock加密 浏览:519
lattice编程软件 浏览:187
如何打开后台服务器 浏览:335
格力空调压缩机阻值 浏览:552
喷码机的单片机原理 浏览:842
如何评估一个算法的效益率 浏览:205
线性代数辅导pdf 浏览:991
贵州戴尔服务器创新服务云主机 浏览:559
如何在小米电视上安装电视家app 浏览:182
苹果手机如何隐藏单个app软件 浏览:963
多路服务器有什么用 浏览:859
如何找培训班app 浏览:580
临时文件夹怎么转到其他盘 浏览:179
android布局按比例 浏览:602
安卓模拟器怎么能当手机用 浏览:885
手机怎样查看服务器ip地址冲突 浏览:812
程序员有没有必要找家教 浏览:783