tail的c语言简单实现

栏目: C · 发布时间: 7年前

内容简介:下面的实现是来自K&R-C的习题实现:下面的例子只简单实现一次输入输出,并不实现系统 tail -f 一样的监控文件的实时输出运行例子:

下面的实现是来自K&R-C的习题实现:

编写程序tail,将输入中的n行打印出来。默认情况下,n的值为10,但可通过一个可选参数改变n的值,因此命令 tail -n 将打印其输入的最后n行。无论输入或n的值是否合理,该程序都应该能正常运行,编写的程序要充分利用存储空间

下面的例子只简单实现一次输入输出,并不实现系统 tail -f 一样的监控文件的实时输出

tail.c

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

#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("%s\n", 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) = '\0';
  return i;
}

运行例子:

cc tail.c && ./a.out -10 < input.txt

以上所述就是小编给大家介绍的《tail的c语言简单实现》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Responsive Web Design

Responsive Web Design

Ethan Marcotte / Happy Cog / 2011-6 / USD 18.00

From mobile browsers to netbooks and tablets, users are visiting your sites from an increasing array of devices and browsers. Are your designs ready? Learn how to think beyond the desktop and craft be......一起来看看 《Responsive Web Design》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具