ubuntu学习(六)----文件编程实现cp指令

1 思路

Linux要想复制一份文件通常指令为:

cp src.c des.c

其中src.c为源文件,des.c为目标文件。

要想通过文件编程实现cp效果,思路如下

1 首先打开源文件 src.c

2 读src到buf

3 创建des.c

4 将buf写入到des.c

5 close两个文件

2 实现

vi demo.c

cpp 复制代码
#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 argc, char **argv)
{
	    /*  0             1               2
			cp            src.c            des.c  3个参数 argc
			||              ||               ||
			argv[0]       argv[1]         argv[2]
		*/     
        int fdSrc;
        int fdDes;

        char *readBuf=NULL;

        if(argc != 3){
                printf("pararm error\n");
                exit(-1);
        }



        fdSrc = open(argv[1],O_RDWR);
        int size = lseek(fdSrc,0,SEEK_END);
        lseek(fdSrc,0,SEEK_SET);

        readBuf=(char *)malloc(sizeof(char)*size + 8);

        int n_read = read(fdSrc, readBuf, size);


        fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);

        int n_write = write(fdDes,readBuf,strlen(readBuf));


        close(fdSrc);
        close(fdDes);

        return 0;
}

gcc demo.c -o mycp

./mycp demo.c ./new.c

vi new.c

相关推荐
学编程的闹钟5 小时前
PHP变量类型转换机制全解析
学习
之歆5 小时前
Linux文件系统与FHS详解
linux·文件系统
zl_dfq7 小时前
Linux 之 【多线程】(死锁、同步与竞态条件、条件变量、pthread_cond_xxx、POSIX信号量、sem_xxx)
linux
学Linux的语莫7 小时前
k8s常用命令
linux·容器·kubernetes
openKylin7 小时前
《2025年度OpenAtom openKylin社区全景案例集》正式发布
linux
CS_Zero7 小时前
Ubuntu安装Claude Code
linux·ubuntu·ai编程·claude
AI360labs_atyun8 小时前
字节AI双王炸来了!Seedance 2.0 + Seedream 5.0
人工智能·科技·学习·百度·ai
A星空1238 小时前
三、Kconfig介绍以及制作menuconfig界面
linux·运维·服务器
zylyehuo8 小时前
Windows & Linux 双系统资料整理
linux·夯实基础
不用89k9 小时前
SpringBoot学习新手项初识请求
java·spring boot·学习