How to write a file with C in Linux?

后端 未结 4 1484
忘了有多久
忘了有多久 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条回答
  •  梦毁少年i
    2021-02-04 13:59

    You have to allocate the buffer with mallock, and give the read write the pointer to it.

    #include 
    #include 
    #include 
    #include 
    #include 
    int main(){
        ssize_t nrd;
        int fd; 
        int fd1;
    
        char* buffer = malloc(100*sizeof(char));
        fd = open("bli.txt", O_RDONLY);
        fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
        while (nrd = read(fd,buffer,sizeof(buffer))) {
            write(fd1,buffer,nrd);
        }   
    
        close(fd);
        close(fd1);
        free(buffer);
        return 0;
    }
    

    Make sure that the rad file exists and contains something. It's not perfect but it works.

提交回复
热议问题