gpt4 book ai didi

在C中复制多个文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:37 25 4
gpt4 key购买 nike

当我尝试在 C 中复制多个文件时遇到问题。它复制目录中的第一个文件,但不再复制。其他文件甚至都打不开,我不知道是怎么回事。有什么想法吗?

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;

最佳答案

为了解决这个问题,我添加了以下几行:

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

有了这个,我得到了当前工作目录的地址。

后来,

    chdir(cwd);

我们必须回来获取后续副本

最终代码:

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;
}

关于在C中复制多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15796503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com