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

相关推荐
辰风沐阳6 小时前
nvm - node 版本管理工具【macOS/Linux】
linux·运维·macos
夜瞬13 小时前
NLP学习笔记01:文本预处理详解——从清洗、分词到词性标注
笔记·学习·自然语言处理
君穆南13 小时前
基于 NFS 与 Rsync 实现跨服务器 Seafile 数据平滑迁移实战
linux·运维·git
bloglin9999913 小时前
scp、rsync远程文件同步
linux·运维·服务器
迦南的迦 亚索的索14 小时前
LINUX环境
linux·运维·服务器
yuanjj8814 小时前
linux下调试域格CLM920 NC5等9x07平台模块 QMI拨号
linux·运维·服务器
IMPYLH14 小时前
Linux 的 printenv 命令
linux·运维·服务器·bash
SilentSamsara14 小时前
SSH 远程管理:密钥登录 + 隧道转发,一次性配置好
linux·运维·服务器·ubuntu·centos·ssh
-Springer-14 小时前
STM32 学习 —— 个人学习笔记11-1(SPI 通信协议及 W25Q64 简介 & 软件 SPI 读写 W25Q64)
笔记·stm32·学习
LN花开富贵14 小时前
【ROS】鱼香ROS2学习笔记一
linux·笔记·python·学习·嵌入式·ros·agv