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

相关推荐
Coder个人博客18 小时前
Linux6.19-ARM64 mm mmu子模块深入分析
大数据·linux·车载系统·系统架构·系统安全·鸿蒙系统
Doro再努力21 小时前
Vim 快速上手实操手册:从入门到生产环境实战
linux·编辑器·vim
wypywyp21 小时前
8. ubuntu 虚拟机 linux 服务器 TCP/IP 概念辨析
linux·服务器·ubuntu
阿蒙Amon21 小时前
TypeScript学习-第10章:模块与命名空间
学习·ubuntu·typescript
AI绘画哇哒哒21 小时前
【干货收藏】深度解析AI Agent框架:设计原理+主流选型+项目实操,一站式学习指南
人工智能·学习·ai·程序员·大模型·产品经理·转行
Doro再努力21 小时前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
senijusene21 小时前
Linux软件编程:IO编程,标准IO(1)
linux·运维·服务器
忧郁的橙子.1 天前
02-本地部署Ollama、Python
linux·运维·服务器
醇氧1 天前
【linux】查看发行版信息
linux·运维·服务器
戌中横1 天前
JavaScript——预解析
前端·javascript·学习