Linux 文件实现终端cp指令

19 篇文章 0 订阅

注:Linux 文件实现终端cp指令 (8、9节)

文件cp的自我实现:

在这里插入图片描述

code:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(int agrc,char **agrv)
{
	int fdSrc;
	int fdDec;
	
	char *readBuf = NULL; //指定一个野指针 
	if(agrc != 3){
		printf("params error !!!");
		exit(-1);
	}//agrc 参数 ,运行参数不能少于3,否则退出 

	fdSrc=open(agrv[1], O_RDWR);	//打开第二参数的内容 
	
	int filesize=lseek(fdSrc,0,SEEK_END); //计算打开文件的大小 
	lseek(fdSrc,0,SEEK_SET);//光标回归起始位置
	readBuf=(char *)malloc(sizeof(char)*filesize + 8); //给野指针传参赋予大小(内存) 
//	ssize_t read(int fd, void *buf, size_t count);
	int n_read = read(fdSrc,readBuf,filesize); //读取打开的原文件文件 

//	int creat(const char *pathname, mode_t mode);
	fdDec=open(agrv[2], O_RDWR | O_CREAT | O_TRUNC, 0600); // 打开/创建目标文件, O_TRUNC清除该文件的内容
	
	int n_write=write(fdDec,readBuf,strlen(readBuf)); // 写目标文件 

	close(fdSrc);	
	close(fdDec);
	return 0;
}

运行结果:

CLC@Embed_Learn:~/LinuxLearn/FILE$ ./a.out demo11.c demo11cp.c
CLC@Embed_Learn:~/LinuxLearn/FILE$ cat demo11.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	char *buf;
	buf=(char *)malloc(sizeof(128));
	
	int n_read  = read(0,buf,128);

	int n_write = write(1,buf,128);
	putchar('\n');
	
	return 0;
}

CLC@Embed_Learn:~/LinuxLearn/FILE$ cat demo11cp.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	char *buf;
	buf=(char *)malloc(sizeof(128));
	
	int n_read  = read(0,buf,128);

	int n_write = write(1,buf,128);
	putchar('\n');
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值