好吧,这可能有一个简单的解决方案,但经过一些搜索和测试后,我仍然感到困惑.. :(
这是我编写的代码片段:
int main(int argc, char *argv[]){
int test;
test = copyTheFile("test.txt", "testdir");
if(test == 1)
printf("something went wrong");
if(test == 0)
printf("copydone");
return 0;
}
int copyTheFile(char *sourcePath, char *destinationPath){
FILE *fin = fopen(sourcePath, "r");
FILE *fout = fopen(destinationPath, "w");
if(fin != NULL && fout != NULL){
char buffer[10000];//change to real size using stat()
size_t read, write;
while((read = fread(buffer, 1, sizeof(buffer), fin)) > 0){
write = fwrite(buffer, 1, read, fout);
if(write != read)
return 1;
}//end of while
}// end of if
else{
printf("Something wrong getting the file\n");
return 0;}
if(fin != NULL)
fclose(fin);
if(fout != NULL)
fclose(fout);
return 0;
}
一些快速说明:我对 C、编程,尤其是文件 I/O 还很陌生。我查阅了 fopen、fread 和 fwrite 的手册页。在查看了一些示例代码后,我想出了这个。我试图只复制一个简单的文本文件,然后将其放在 destinationPath 指定的目标文件夹中。
我要放置文本文件的文件夹叫testdir,我要复制的文件叫test.txt。
我试图在 copyFile 函数中使用的参数是:
- "test.txt""testdir"
- ".../Desktop/project/test.txt"".../Desktop/project/testdir"
- "/Desktop/project/test.txt""/Desktop/project/testdir"
每次尝试时,我都会得到打印语句“获取文件时出错”。我在想这可能是因为“testdir”是文件夹而不是文件,但是我该如何复制到文件夹?
抱歉,如果这是一个非常基本的问题,我只是遇到了麻烦,所以任何建议都很棒!
此外,如果您想提供更多帮助,“copyTheFile”功能应该可以复制文件,而不管格式如何。所以如果它是 .jpg 或它应该复制它的东西。如果你们中的任何人发现它有问题,请告诉我。
这是 Linux 上的 ISO/POSIX/C89/C99。
最佳答案
开始时,您需要包含 stdio.h
以提供 FILE
和 I/O 函数声明:
#include <stdio.h>
除此之外,您的程序对我来说编译和工作正常。不幸的是,如果不使用 stat()
检测目标是否为目录,则无法复制到目录,如果是,则在打开文件之前附加文件名。
一些其他的小建议:
诸如
4096
之类的 2 字节幂的缓冲区可能更高效,因为它符合文件系统和磁盘访问模式通常,返回状态代码的 C 函数使用
0
表示成功,使用其他值(例如1
)表示失败,因此交换返回值可能会更少令人困惑当
fopen
、fread
或fwrite
等标准库函数失败时,最好使用perror(NULL);
或perror("error prefix");
来报告它,它可能类似于:$ ./a.out ... error prefix: No such file or directory
关于c - 无法在 C 中测试复制文件功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19873594/