質問

I have a problem when I try to copy multiple files in C. It copies the first file in the directory, but no more. Other files are not even open and I do not know how the problem is. Any idea?

bool copyFileToDirectory(char *file, char *directory){
    int input_fd, output_fd;
    ssize_t ret_in, ret_out;
    char* buffer[2048];
    struct stat fileStat;

    /* Check permissions */
    access (directory, W_OK);
    if (errno == EACCES) {
        perror("Output file not writable");
        return false;
    }
    if (errno == EROFS) {
        perror("Output file not writable (read-only)");
        return false;
    }
    int rval = access (file, R_OK);
    if (rval != 0) {
        printf ("Input file is not readable (access denied)\n");
        return false;
    }

    /* Copy */
    input_fd = open (file, O_RDONLY);
    stat(file, &fileStat);

    chdir(directory);

    output_fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    chmod(file, fileStat.st_mode);

    while((ret_in = read (input_fd, &buffer, 2048)) > 0){
        ret_out = write (output_fd, &buffer, (ssize_t) ret_in);
        if(ret_out != ret_in){
            perror("An error has ocurred during the process\n");
            return false;
        }
    }

    close(input_fd);
    close(output_fd);

    return true;

}

役に立ちましたか?

解決

To solve the problem, I added the following lines:

    char cwd[1024];
    getcwd(cwd, 1024);

With this, I got the address of the current working directory.

And later,

    chdir(cwd);

We have to come back for subsequent copies.

Final code:

bool copyToDirectory(char *file, char *directory){
    char cwd[1024];
    getcwd(cwd, 1024);
    int input_fd, output_fd;
    ssize_t ret_in, ret_out;
    char* buffer[2048];
    struct stat fileStat;

    /* Check permissions */
    access (directory, W_OK);
    if (errno == EACCES) {
        perror("Output file not writable");
        return false;
    }
    if (errno == EROFS) {
        perror("Output file not writable (read-only)");
        return false;
    }
    int rval = access (file, R_OK);
    if (rval != 0) {
        printf ("Input file is not readable (access denied)\n");
        return false;
    }

    /* Copy */
    input_fd = open (file, O_RDONLY);
    stat(file, &fileStat);

    chdir(directory);

    output_fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    chmod(file, fileStat.st_mode);

    while((ret_in = read (input_fd, &buffer, 2048)) > 0){
        ret_out = write (output_fd, &buffer, (ssize_t) ret_in);
        if(ret_out != ret_in){
            perror("An error has ocurred during the process\n");
            return false;
        }
    }

    close(input_fd);
    close(output_fd);

    chdir(cwd);

    return true; 
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top