【问题标题】:Copy File to a Directory in C将文件复制到 C 中的目录
【发布时间】:2015-05-02 01:17:14
【问题描述】:

如何用 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(),它将只在当前目录中创建。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: c directory copy


    【解决方案1】:

    你可以使用 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");
    

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 1970-01-01
      • 2021-06-16
      • 2020-06-22
      • 2021-02-15
      • 2014-07-25
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多