📌  相关文章
📜  将一个文本文件的内容附加到另一个文本文件的 C 程序

📅  最后修改于: 2021-09-06 06:08:25             🧑  作者: Mango

先决条件: C中的文件处理

给定源和目标文本文件,任务是将源文件的内容附加到目标文件,然后显示目标文件的内容。
例子:

Input: 

file1.text
This is line one in file1
Hello World.
file2.text
This is line one in file2
Programming is fun.

Output: 
 
This is line one in file2
Programming is fun.
This is line one in file1
Hello World.


方法:

  1. 用“a+”(追加和读取)选项打开file1.txtfile2.txt,这样文件之前的内容不会被删除。如果文件不存在,它们将被创建。
  2. 向目标文件显式写入换行符(“\n”)以增强可读性。
  3. 将内容从源文件写入目标文件。
  4. 将 file2.txt 中的内容显示到控制台(stdout)。
C
// C program to append the contents of
// source file to the destination file
// including header files
#include 
 
// Function that appends the contents
void appendFiles(char source[],
                 char destination[])
{
    // declaring file pointers
    FILE *fp1, *fp2;
 
    // opening files
    fp1 = fopen(source, "a+");
    fp2 = fopen(destination, "a+");
 
    // If file is not found then return.
    if (!fp1 && !fp2) {
        printf("Unable to open/"
               "detect file(s)\n");
        return;
    }
 
    char buf[100];
 
    // explicitly writing "\n"
    // to the destination file
    // so to enhance readability.
    fprintf(fp2, "\n");
 
    // writing the contents of
    // source file to destination file.
    while (!feof(fp1)) {
        fgets(buf, sizeof(buf), fp1);
        fprintf(fp2, "%s", buf);
    }
 
    rewind(fp2);
 
    // printing contents of
    // destination file to stdout.
    while (!feof(fp2)) {
        fgets(buf, sizeof(buf), fp2);
        printf("%s", buf);
    }
}
 
// Driver Code
int main()
{
    char source[] = "file1.txt",
         destination[] = "file2.txt";
 
    // calling Function with file names.
    appendFiles(source, destination);
 
    return 0;
}


输出:

下面是上述程序的输出:

时间复杂度:O(N)
辅助空间复杂度:O(1)

想要从精选的视频和练习题中学习,请查看 C 基础到高级C 基础课程。