Linux用C语言代码实现cat命令,实现cat -n命令

Linux用C语言代码实现cat命令,实现cat -n命令,第1张

C语言代码实现cat命令:

#include
#include
#include

#include
#include

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
#include
#include

#include
#include

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下有些输入可能不太一样

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/791386.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-05
下一篇2022-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存