Linux C implements cp command

Linux C implements cp command

1.Analysis

The cp command essentially copies the contents of one file to another file. It is not a shortcut (soft link), so it is easy to think of file IO. We need to keep reading from source file A and keep writing to the target file. Among B, that's it.

2.Code

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

int main(){
    
    
    //1.设置读文件的文件描述符
    int srcfd = open("english.txt", O_RDONLY);
    if(srcfd == -1) {
    
    
        perror("open source file");
    }

    //2.设置写文件的文件描述符
    int dstfd = open("copy.txt", O_WRONLY | O_CREAT, 0777);
    if(dstfd == -1) {
    
    
        perror("open destination file");
    }

    //3.读数据并且写入
    char buf[1024] = {
    
    0};
    int len = 0;
    while((len=read(srcfd, buf, sizeof(buf))) > 0) {
    
    
        write(dstfd, buf, len);
    }

    //4.关闭文件描述符
    close(dstfd);
    close(srcfd);
    return 0;
}

First of all, you have to make sure that the source file exists, which is the same as the requirement of the cp command. Then the target file is used in the second method with permission settings. In the open of writing the file, open is used. The first usage. Regarding the function parameters and return values ​​of read, you can get help from man documents, such as man 2 open. Learning to read the documents will indeed get twice the result with half the effort, related header files, a series of usages of the same name function, the specific meaning of the parameters, and the return value. Situations corresponding to different error numbers.

3. Areas that can be improved

If you want to be more like the cp command, set both the target file and the source file as parameters of the program, and then make a judgment on the source file. Regarding the permissions of the created target file, you can use the related functions of the file descriptor to obtain the relevant information of the source file, and then set the same permissions for the target file (such as 0755).

Guess you like

Origin blog.csdn.net/qq_43847153/article/details/128499825