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

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

下面的例子使用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 */

/**

* @filelast20.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 = s2p >= s1--p) {

if (*p == c)

return p

}

return NULL

}

#define READSIZE1024

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 = 0i <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

}

输入"tail -n 500 aaa.txt"即可,这个意思是查看aaa.txt记事本的最后500个文字,下面我们来了解一下linux:

1.Linux内核最初只是由芬兰人李纳斯·托瓦兹(Linus Torvalds)在赫尔辛基大学上学时出于个人爱好而编写的。

2.Linux是一套免费使用和自由传播的类Unix *** 作系统,是一个基于POSIX和UNIX的多用户、多任务、支持多线程和多CPU的 *** 作系统。

3.Linux能运行主要的UNIX工具软件、应用程序和网络协议。它支持32位和64位硬件。Linux继承了Unix以网络为核心的设计思想,是一个性能稳定的多用户网络 *** 作系统。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8401754.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-16
下一篇 2023-04-16

发表评论

登录后才能评论

评论列表(0条)

保存