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

相关推荐
代码中介商12 分钟前
Linux 信号处理与进程控制深度解析
linux·运维·信号处理
姚青&23 分钟前
Linux 文件处理命令
linux·运维·服务器
黑眼圈子24 分钟前
动态规划问题专项练习(未编辑完成...
学习·算法·动态规划
Aliex_git25 分钟前
Nuxt 学习笔记(一)
前端·笔记·学习
烤麻辣烫27 分钟前
json与fastjson
前端·javascript·学习·json
tryqaaa_41 分钟前
学习日志(二)【linux全部命令,http请求头{有例题},Php语法学习】
linux·学习·http·php·web
sxjk19871 小时前
WPS表格REGEXP公式提取车牌学习
学习·wps·表格·数据处理
万法若空1 小时前
ANSI转义码详解
linux·c++
计算机安禾1 小时前
【Linux从入门到精通】第21篇:Shell脚本开篇——什么是Shell?写第一个Hello World
linux·运维·服务器
Lumos_7771 小时前
Linux -- 系统调用
linux·运维·算法