先决条件: 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.
方法:
- 使用“ a +”(添加和读取)选项打开file1.txt和file2.txt,以便不删除文件的先前内容。如果文件不存在,将创建它们。
- 显式地将换行符(“ \ n”)写入目标文件以提高可读性。
- 将内容从源文件写入目标文件。
- 将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基础课程》。