Implementation of Linux cp command

CP commands

This article will show the code to implement the Linux cp command


 

Article Directory

 


Preface

Have you ever wondered how the command in Linux implements the function of the command? Here I will introduce the code.

 

1. The idea of ​​realizing the CP command

To copy the content of a file to an existing file, or copy to a newly created file, the first step : open the file to be copied; the second step : copy the file to the buffer area; the third step : Open and create a new file; Step 4 : Write the contents of the buffer area to the newly created file; Step 5 : Close the file

Second, the steps

1. Introduce the library

code show as below:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


 

2. Code to implement CP commands

code show as below:

int main(int argc,char **argv)
{
        int fdSrc;
        int fdDes;
        char *readBuf = NULL;

    //判断使用该命令的方式是否正确 
        if(argc != 3){
                printf("param error\n");
                exit(-1);
        }

    //第一步:打开待复制的文件
        fdSrc = open(argv[1],O_RDWR);
        int size = lseek(fdSrc,0,SEEK_END);
        lseek(fdSrc,0,SEEK_SET);    //将光标移动待文件开头
    
    //第二步:将待复制的文件读取到缓存区 readBuf
        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,size);

    //第五步:关闭文件,以达到保护文件的作用
        close(fdSrc);
        close(fdDes);
        return 0;
}


 


to sum up

After knowing how the commands are implemented, are you curious about functions such as open(), read(), write(), etc. How do these functions implement these functions?

Guess you like

Origin blog.csdn.net/weixin_49472648/article/details/108891328