C - Write the program tail which prints the last n lines of its input

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * Write the program tail, which prints the last n lines of its input. By default,
 * n is set to 10, let us say, but it can be changed by an optional argument so that
 * tail -n
 * prints the last n lines. The program should behave rationally no matter how
 * unreasonable the input or the value of n. Write the program so it makes the best
 * use of available storage.
 *
 * Tail.c - by FreeMan
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINES        1024
#define MAXINPUT        10240
#define DEF_NUM_LINES   10

int  getlines(char *);
void parse_args(int, char **);

char  linestr[MAXINPUT];
char *lineptr[MAXLINES];
int num_of_lines = DEF_NUM_LINES;

int main(int argc, char *argv[])
{
	int lines;
	int ltp = 0;
	int i;
	int c;

	*lineptr = linestr;

	/* Parse the argument strings passed to the program */
	if (argc > 1) {
		parse_args(argc, argv);
	}

	/* Get the input from the user */
	lines = getlines(linestr);

	if (num_of_lines == 0) {
		num_of_lines = 10;
	}
	ltp = lines < num_of_lines ? lines : num_of_lines;
	printf("\n>>> Printing %d line(s):\n", ltp);
	if (ltp == DEF_NUM_LINES) {
		printf(">>> The default number of lines to print is ");
		printf("%d\n", DEF_NUM_LINES);
	}
	printf("\n");

	for (i = lines; i > 0; i--)
	{
		while ((c = *lineptr[0]++) != '\n')
		{
			if (i <= ltp)
			{
				printf("%c", c);
			}
		}
		if (c == '\n' && i <= ltp)
		{
			printf("\n");
		}
	}

	return 0;
}

int getlines(char *buffer)
{
	int i, count = 0;
	char c;

	for (i = 0; (c = getchar()) != EOF && i < MAXINPUT; i++) {
		*buffer++ = c;
		if (c == '\n') {
			lineptr[++count] = buffer;
		}

	}
	*buffer++ = '\0';

	return count;
}

void parse_args(int argc, char **argv)
{
	char c;

	while (--argc > 0 && (*++argv)[0] == '-') {
		c = *++argv[0];
		switch (c) {
		case 'n':
			num_of_lines = atoi(*(argv + 1));
			break;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值