How to write a file with C in Linux?

后端 未结 4 1481
忘了有多久
忘了有多久 2021-02-04 13:36

I want to rewrite the \"cp\" command of Linux. So this program will work like #./a.out originalfile copiedfile. I can open the file, create new file but can\'t writ

4条回答
  •  死守一世寂寞
    2021-02-04 13:47

    You need to write() the read() data into the new file:

    ssize_t nrd;
    int fd;
    int fd1;
    
    fd = open(aa[1], O_RDONLY);
    fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    while (nrd = read(fd,buffer,50)) {
        write(fd1,buffer,nrd);
    }
    
    close(fd);
    close(fd1);
    

    Update: added the proper opens...

    Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

提交回复
热议问题