如何在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(),它将仅在当前目录中创建。
任何帮助将不胜感激。
谢谢!
答案 0 :(得分:2)
您可以使用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");