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

熱點內容
資料庫查詢系統源碼 瀏覽:617
php5314 瀏覽:358
完美國際安裝到哪個文件夾 瀏覽:668
什麼app可以掃一掃做題 瀏覽:539
程序員編碼論壇 瀏覽:923
淘點是什麼app 瀏覽:659
中國高等植物pdf 瀏覽:453
51單片機時間 瀏覽:182
後台如何獲取伺服器ip 瀏覽:267
單片機流水燈程序c語言 瀏覽:234
程序員第二職業掙錢 瀏覽:239
運行里怎麼輸入伺服器路徑 瀏覽:840
pythonstepwise 瀏覽:509
劉一男詞彙速記指南pdf 瀏覽:64
php認證級別 瀏覽:368
方舟編譯啥時候推送 瀏覽:1011
php手機驗證碼生成 瀏覽:675
哲學思維pdf 瀏覽:14
凌達壓縮機有限公司招聘 瀏覽:534
weblogic命令部署 瀏覽:38