当我尝试在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;
}
答案 0 :(得分:1)
为了解决这个问题,我添加了以下几行:
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;
}