C语言用标准IO实现linux的cp命令

代码如下,在linux下测试ok:

/****************************************
*功能:用标准io实现cp命令
*作者:lml   时间:2020年4月13日22:19:39
****************************************/

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

int main(int argc, const char *argv[])
{
	FILE *fd1;
	FILE *fd2;

	fd1 = fopen(argv[1],"r"); //文件名从终端读入,打开的文件必须存在,不然怎么复制呢?
	fd2 = fopen(argv[2],"w+");//文件名从终端读入,打开的文件可以不存在,自己会创建,存在的也会覆盖,

	char *ret = NULL;
	char buf[20]="";

	while(1){
		ret = fgets(buf,6,fd1);
		if(ret == NULL){
			perror("fgets");
			break;
		}
		//读一笔就写一笔		
		else{
			if(fputs(buf,fd2) < 0) {
				perror("fputs");
				break;
			} 
		}
	}
	fclose(fd1);
	fclose(fd2);
	return 0;
}

最后提示:
1、在linux下运行,用gcc编译后,运行应该这样键入:./a.out 1.txt 2.txt
2、键入的字符意思是执行程序 把1.txt文件复制新的一份并命名为2.txt
3、在程序中省略了错误检查的代码,比如fopen函数是否正常返回没有做检查,如果真正项目,那是必不可少的,希望读者知情。

发布了4 篇原创文章 · 获赞 2 · 访问量 22

猜你喜欢

转载自blog.csdn.net/qq_19693355/article/details/105499957