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 分钟前
Linux驱动阻塞与非阻塞访问的理解
linux·嵌入式系统
无敌贵点大王7 分钟前
RTThread学习记录13——关于要使用一个外设,RTThread与cubemx到底要怎么配合?
c语言·stm32·学习·rtthread
..Dauntless..12 分钟前
【Linux】进程地址空间初步理解
linux·运维·服务器
Julien200420 分钟前
Docker 网络(一)
linux·运维·服务器·ssh·学习方法
杨云龙UP1 小时前
一次数据库查询缓慢故障复盘:大表数据增长、SQL全表扫描导致系统响应异常
linux·运维·服务器·数据库·sql·mysql
喜欢打篮球的普通人1 小时前
MiniMind 学习笔记(十二):Pretrain 实操——从版本梳理到 8GB 显卡上的真实训练
人工智能·笔记·学习
PellyKoo2 小时前
【linux运维】ubuntu+samba 用户组独占目录权限配置踩坑记
linux·运维·ubuntu
AR-26710-2 小时前
Linux Day15——系统管理复习
linux·运维
高山有多高2 小时前
【Linux笔记】Linux自定义Shell
linux·c++
m4Rk_2 小时前
【论文阅读】Agent 记忆机制(87):VizoMem——把文本历史转化为可检索的视觉记忆
论文阅读·人工智能·学习·开源·github