您的问题并非100%明确,但这是您将文件附加到另一个文件的方式.我使用了一个1字节的缓冲区,例如.您也可以以块的形式复制文件.
FILE *source = fopen("to_copy", "rb");
/* I'm assuming it opened OK */
FILE *dest = fopen("dest", "ab");
/* I'm assuming it opened OK, again */
char byte;
while (!feof(source))
{
fread(&byte, sizeof(char), 1, source);
fwrite(&byte, sizeof(char), 1, dest);
}
fclose(source);
fclose(dest);
Run Code Online (Sandbox Code Playgroud)
要将文件的内容复制到文件tail的末尾head,请打开tail(文本或二进制)阅读和head追加;像这样(根据计划9的模型cat.c。):
#include <stdio.h>
#include <stdlib.h>
void
append(FILE *head, FILE *tail)
{
char buf[BUFSIZ];
size_t n;
while ((n = fread(buf, 1, sizeof buf, tail)) > 0)
if (fwrite(buf, 1, n, head) != n)
abort();
if (ferror(tail))
abort();
}
int main(void)
{
FILE *head = fopen("head", "ab");
FILE *tail = fopen("tail", "rb");
if (!head || !tail)
abort();
append(head, tail);
fclose(head);
fclose(tail);
exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
适当的错误报告留给读者练习。