導航:首頁 > 操作系統 > 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相關的資料

熱點內容
按鍵精靈自定義圖層命令 瀏覽:351
魅藍3手機音視頻文件夾 瀏覽:943
安卓手機製表怎麼換行 瀏覽:213
牆柱搭接箍筋怎麼加密 瀏覽:454
怎麼加密不讓人打開 瀏覽:334
2g3g演算法 瀏覽:204
python可以在net開發 瀏覽:932
編程里的hr啥意思 瀏覽:409
上海php兼職 瀏覽:728
順豐app如何驗證學生 瀏覽:380
伺服器mac地址過濾器 瀏覽:942
程序員一年內被開除 瀏覽:456
福建文檔課件加密企業 瀏覽:790
appstore美國的界面怎麼看呀 瀏覽:533
hlt單片機 瀏覽:325
CA的命令 瀏覽:685
安卓怎麼傳王者應用給蘋果 瀏覽:922
aws雲伺服器自建 瀏覽:840
如何更換伺服器登錄網站 瀏覽:700
java修改ip地址 瀏覽:838