C语言代码实现cat命令:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main(int argc, char* argv[])
{
char buf[30];
int size=0;
//int line=0;
if(argc==1){
printf("wrong number of arguments.\n");
return -1;
}
int fd=open(argv[1], O_RDONLY);
if(fd==-1){
printf("open file failed.\n");
return -1;
}
while(size=read(fd, buf, 29)){
buf[size]='\0';
fputs(buf, stdout);
}
return 0;
}
C语言代码实现cat -n命令:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main(int argc, char* argv[])
{
char buf[1024]={0};
int size=0;
int line=0;
FILE *fd;
fd=fopen(argv[1], "r");
if(argc==1){
printf("wrong number of arguments.\n");
return -1;
}
if(fd==NULL){
printf("open file failed.\n");
return -1;
}
while(fgets(buf, sizeof(buf), fd)) //按行读取
if(buf[0]!='\n')
{
line++;
printf("%d\t%s",line,buf);
}
printf("\n");
fclose(fd);
return 0;
}
建议自己敲一遍,windows下和Linux下有些输入可能不太一样