Implement CP instructions under linux

Linux implements cp instruction programming idea mian(int argc char **argv)

Normally use the CP instruction cp src.c des.c. The total three parameters are argc, argv[0]-cp, argv[1]-src.c, argv[2]-des.c

Programming ideas
    1. Open the file src.c
    2. Read the file: read the contents of src.c into buf
    3. Create a new file des.c
    4. Write to the new file: write the contents of buf to des. c in
    5. Close the two files   

#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)
{
        char *buf = "laihamabaoqingwa!";
        char *readBuff = NULL;
        int fdSrc;
        int fdDes;
        if(argc != 3){
                printf("pararm error\n");
                exit(-1);
        }

        fdSrc = open(argv[1],O_RDWR);

        int size = lseek(fdSrc,0,SEEK_END);
        readBuff =(char *)malloc(sizeof(char)*size+8);

        lseek(fdSrc,0,SEEK_SET);

        //int n_read = read(fdSrc,readBuff,1024);
        int n_read = read(fdSrc,readBuff,size);

        //fdDes = open(argv[2],O_RDWR|O_CREAT,0600);
        fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);

        //打开des.c没有就创建O_CREAT,O_TRUNC是保证先清楚des.c原有的内容

        int n_write = write(fdDes,readBuff,strlen(readBuff));

        close(fdSrc);


        close(fdDes);

        return 0;
}

Guess you like

Origin blog.csdn.net/qq_44848795/article/details/123563589