linux中head、tail命令的实现
2015-11-11 09:08
666 查看
head命令:
tail命令:
#include <stdio.h> #include <stdlib.h> #define ARGC_SIZE1 2 #define ARGC_SIZE2 3 #define PRINTF_LINE 10 enum ERR { EXT_SUCCESS, ARGC_ERROR, FILE_OPEN_ERROR }; int main(int argc,char *argv[]) { FILE *fp; char c,*file_name; int iLine = 0; int k = 0; if (argc < ARGC_SIZE1) { printf("please use FILENAME\n"); return ARGC_ERROR; } if(argc == ARGC_SIZE1) { iLine = PRINTF_LINE; file_name = argv[1]; } else if(argc == ARGC_SIZE2) { iLine = (-atoi(argv[1])); iLine = (iLine>0)?iLine:(0-iLine); file_name = argv[2]; } fp = fopen(file_name,"r"); if(fp == NULL) { perror("head open:"); fclose(fp); return FILE_OPEN_ERROR; } while((c=fgetc(fp))!= EOF) { putchar(c); if(c == '\n') k++; if((k)==iLine) break; } fclose(fp); return EXT_SUCCESS; }
tail命令:
#include <stdio.h> #include <stdlib.h> #define ARGC_SIZE1 2 #define ARGC_SIZE2 3 #define PRINTF_LINE 10 enum ERR { EXT_SUCCESS, ARGC_ERROR, FILE_OPEN_ERROR }; int main(int argc,char *argv[]) { FILE *fp; char c,*file_name; int iLine = 0; int num = 0; int m = 0,k = 0; if (argc < ARGC_SIZE1) { printf("please use FILENAME\n"); return ARGC_ERROR; } if(argc == ARGC_SIZE1) { iLine = PRINTF_LINE; file_name=argv[1]; } else if(argc == ARGC_SIZE2) { iLine = (atoi(argv[1])); iLine = (iLine>0)?iLine:(0-iLine); file_name=argv[2]; } fp = fopen(file_name,"r"); if(fp == NULL) { perror("tail open:"); fclose(fp); return FILE_OPEN_ERROR; } while((c=fgetc(fp))!=EOF) { if(c=='\n') num++; } num++; fseek(fp,0,SEEK_SET); while(((c=fgetc(fp))!=EOF) && (k<num-iLine)) { m++; if(c=='\n') k++; } fseek(fp,m,SEEK_SET); while((c=fgetc(fp))!= EOF) { putchar(c); } fclose(fp); return EXT_SUCCESS; }
相关文章推荐
- linux下的用户和用户组的管理
- 修复linux系统引导
- centos配置嵌入式开发环境2
- CentOS6.0搭建嵌入式开发环境
- 给Linux安装上中文的man手册
- Linux和Windows通信服务配置
- 在centos中安装rar压缩工具
- linux vim基本操作命令
- 在Linux中安装更新或安装gcc
- 在Linux中安装和使用wps
- 使用linux系统,破解wifi过程
- Linux下doxygen、graphviz生成chm文档
- Centos5.8 x86_64下安装mysql
- Linux-curl 的使用
- linux文件管理
- Linux发行版Ubuntu与Debian之间有哪些不同之处
- VirtualBox安装linux后无法上网
- CentOS安装gcc
- CentOS安装mysql
- centos防火墙开发新端口