将文件复制到C中的目录
Copy File to a Directory in C
你如何用 C 编写一个程序来将文件(由源文件路径给出,例如 /input/input.txt)复制到一个存在的目录中?目录中的复制文件必须与输入文件同名。
这是我目前的代码片段:
int copyfile1(char* infilename, char* outfileDir) {
FILE* infile; //File handles for source and destination.
FILE* outfile;
DIR* outfileDir;
infile = fopen(infilename, "r"); // Open the input and output files.
if (infile == NULL) {
open_file_error(infilename);
return 1;
}
outfileDir = opendir(outfilename);
if (outfile == NULL) {
open_file_error(outfilename);
return 1;
}
outfile = fopen(infilename, "w");
我卡在这里了。我现在不确定如何处理输出文件,因为它应该在目录中。如果我使用 fopen(),它将只在当前目录中创建。
任何帮助将不胜感激。
谢谢!
您可以使用 basename(3) -- http://linux.die.net/man/3/dirname
int copyfile1(char* infilename, char* outfileDir) {
FILE* infile; //File handles for source and destination.
FILE* outfile;
char outfilename[PATH_MAX];
infile = fopen(infilename, "r"); // Open the input and output files.
if (infile == NULL) {
open_file_error(infilename);
return 1;
}
sprintf(outfilename, "%s/%s", outfileDir, basename(infilename))
outfile = fopen(outfilename, "w");
你如何用 C 编写一个程序来将文件(由源文件路径给出,例如 /input/input.txt)复制到一个存在的目录中?目录中的复制文件必须与输入文件同名。
这是我目前的代码片段:
int copyfile1(char* infilename, char* outfileDir) {
FILE* infile; //File handles for source and destination.
FILE* outfile;
DIR* outfileDir;
infile = fopen(infilename, "r"); // Open the input and output files.
if (infile == NULL) {
open_file_error(infilename);
return 1;
}
outfileDir = opendir(outfilename);
if (outfile == NULL) {
open_file_error(outfilename);
return 1;
}
outfile = fopen(infilename, "w");
我卡在这里了。我现在不确定如何处理输出文件,因为它应该在目录中。如果我使用 fopen(),它将只在当前目录中创建。
任何帮助将不胜感激。
谢谢!
您可以使用 basename(3) -- http://linux.die.net/man/3/dirname
int copyfile1(char* infilename, char* outfileDir) {
FILE* infile; //File handles for source and destination.
FILE* outfile;
char outfilename[PATH_MAX];
infile = fopen(infilename, "r"); // Open the input and output files.
if (infile == NULL) {
open_file_error(infilename);
return 1;
}
sprintf(outfilename, "%s/%s", outfileDir, basename(infilename))
outfile = fopen(outfilename, "w");