c语言读文件tail,tail的c语言简单实现

下面的实现是来自K&R-C的习题实现:编写程序tail,将输入中的n行打印出来。默认情况下,n的值为10,但可通过一个可选参数改变n的值,因此命令 tail -n 将打印其输入的最后n行。无论输入或n的值是否合理,该程序都应该能正常运行,编写的程序要充分利用存储空间下面的例子只简单实现一次输入输出,并不实现系统 tail -f 一样的监控文件的实时输出

tail.c#include

#include

#include

#define MAXLINE 1000

void tail(int n);

static int mygetline(char *s, int len);

int main(int argc, char *argv[]) {

int n = 10;

char *arg;

while (--argc > 0) {

arg = *(++argv);

if (*arg == '-') {

n = atoi(++arg);

}

}

tail(n);

}

void tail(int n) {

printf("show %d lines: n", n);

int count = 0;

char *lines[n];

char s[MAXLINE];

int w;

char *p;

while ((w = mygetline(s, MAXLINE)) != 0) {

p = malloc(w);

if (p == NULL) {

printf("memory alloc error");

return;

} else {

strcpy(p, s);

if (count >= n) {

free(lines[count % n]);

}

lines[count % n] = p;

count++;

}

}

int start = 0;

int end = n;

if (count >= n) {

start = count;

end = count + n;

}

for (; start < end; start++) {

printf("%sn", lines[start % n]);

free(lines[start % n]);

}

}

static int mygetline(char *s, int len) {

static char c;

if (c == EOF) {

return 0;

}

int i = 0;

while ((c = getchar()) != 'n' && c != EOF && i < len - 1) {

*(s + i++) = c;

}

if (c == 'n') {

*(s + i) = 'n';

}

*(s + i) = '

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值