【问题标题】:How to copy the contents of a file to a new file, given a file pointer? [closed]给定文件指针,如何将文件的内容复制到新文件? [关闭]
【发布时间】:2020-07-18 23:08:22
【问题描述】:

在Linux机器上的C语言中,给定一个指向当前目录中文件的文件指针,我如何将该文件的内容复制到子目录中的新文件中。

带有目录结构(home,文件名和目录名任意):

home/
  |________file.txt
  |________source.c
  |________subdirectory/

我希望source.c 文件进行system() 调用,该调用将在subdirectory/ 中创建一个名为copy.txt(名称任意)的文件,并将file.txt 的内容复制到复制文件中。

生成的目录结构将是:

home/
  |________file.txt
  |________source.c
  |________subdirectory/
             |________copy.txt

其中 file.txt 和 copy.txt 的内容完全相同。

【问题讨论】:

标签: c linux file-io copy


【解决方案1】:

由于你在源文件上只打开了一个流指针,所以你不能通过调用system进行复制,但是直接复制内容很容易:

#include <stdio.h>
#include <unistd.h>

int copyfile(FILE *f1) {
    long pos;
    FILE *f2;
    int c;

    if (mkdir("subdirectory", 0644))
        return -1;
    if ((f2 = fopen("subdirectory/copy.txt", "w")) == NULL)
        return -1;
    pos = ftell(f1);
    rewind(f1);
    while ((c = getc(f1)) != EOF) {
        putc(c, f2);
    }
    fseek(pos, SEEK_SET, f1);
    return fclose(f2);
}

【讨论】:

    【解决方案2】:

    如果你知道源文件的名字,你可以调用

    system("mkdir subdirectory && cp ./file.txt ./subdirectory/copy.txt");
    

    这将首先创建子目录,然后将文件复制到其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多