给定文件指针,如何将文件内容复制到新文件?

How to copy the contents of a file to a new file, given a file pointer?

在 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 具有完全相同的内容。

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

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

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

由于在源文件上只打开了一个流指针,无法通过调用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);
}