#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 4096
int main(int ac,char *av[]){
/*创建输入文件的文件描述符*/
int in_fd;
int len = sizeof(char);
char buf;
/*对输入时的参数进行判定*/
if(ac != 3){
fprintf(stderr,"usage: %s source destination\n",*av);
exit(0);
}
char *line = av[1];
int nline;
/*我只处理第二个字符串av[1]的前两个数字*/
if(line[2]=='\0'){
nline = (int)line[1]-48;
}else{
nline = ((int)line[1]-48)*10+((int)line[2]-48);
}
if((nline>=100)||(line[0]!='-'))
{
printf("Please input '-n' as the param\n");
exit(0);
}
if((in_fd=open(av[2],O_RDONLY))==-1){
printf("Can not open:%s\n",av[2]);
exit(1);
}
while(((len=read(in_fd,&buf,len))>0)&& (nline > 0)){
if((write(1,&buf,len))!=len){
printf("Write error to\n");
exit(1);
}
if(buf == '\n'){
nline--;
}
}
if(close(in_fd)==-1){
printf("Error close files\n");
exit(1);
}
return 0;
}
Shell命令编写——查看文件的命令head -n
最新推荐文章于 2023-12-10 07:15:00 发布