简体   繁体   English

将文件复制到C中的目录

[英]Copy File to a Directory in C

How do you write a program in C that can copy a file (given by source file path, eg. /input/input.txt) into an existed directory? 您如何用C语言编写一个程序,可以将文件(由源文件路径指定,例如/input/input.txt)复制到现有目录中? The copy file in the directory must have the exact same name as the input file. 目录中的复制文件必须与输入文件具有完全相同的名称。

This is the piece of code I have so far: 这是我到目前为止拥有的代码:

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");

I get stuck here. 我被困在这里。 I'm not sure how to handle the output file now, since it is supposed to be in the directory. 我不确定现在应该如何处理输出文件,因为它应该在目录中。 If I use fopen(), it will be create in the current directory only. 如果我使用fopen(),它将仅在当前目录中创建。

Any help will be appreciated. 任何帮助将不胜感激。

Thanks! 谢谢!

You can use basename(3) -- http://linux.die.net/man/3/dirname 您可以使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM