C implementation - merge characters from two files into a new file (detailed)

Write in front (import)

       Be sure to execute the program before: "Create 3 text documents on the desktop", named A, B, C. To avoid program execution errors, of course, you can also modify the relative path of file opening, and modify the path of file A.txt in "fopen("A.txt", "r")" in the following program by yourself.

Code

        Idea: First get the elements in each file and store them in a character array, then merge the arrays, and finally write the elements to the file. (The program has been annotated in detail and will not be repeated here)

//导入头文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//主函数
int main(){
    FILE *fa,*fb,*fc;//定义3个文件指针,指向文件 A、B、C 
    int i,j,k;//控制循环 
    char str[100],str1[100];
    //判断文件 A 是否存在 
    if((fa=fopen("A.txt","r"))==NULL){
        printf("文件A不存在!\n");
        exit(0);
    }
    fgets(str,99,fa);//存储A内容到数组 str 中 
    fclose(fa);//关闭文件A 
    //判断文件 B 是否存在 
    if((fb=fopen("B.txt","r"))==NULL){
        printf("文件B不存在!\n");
        exit(0);
    }
    fgets(str1,100,fb);//存储A内容到数组 str1 中 
    fclose(fb);//关闭文件B 
    strcat(str,str1);//将字符数组 str1 中内容存储到字符数组 str 中     
    //判断文件 C 是否存在 
    if((fc=fopen("C.txt","w"))==NULL){
        printf("文件C不存在!\n");
        exit(0);
    }
    fputs(str,fc);//将数组 str 中内容写到文件 C 中 
    fclose(fc);//关闭文件 C 
    printf("信息合并完成! 请到文件 C 中查看.\n");//信息提示 
    return 0;
}

Running results (three-part display)

1. Data in file A:

 

2. Data in file B

 

3. The merged data in file C

 (1) In the program, the default file location is "source program storage location or desktop", then open the file to view , as shown in Figure (2)

(2) As shown in the figure below, the contents of the file:

 

Guess you like

Origin blog.csdn.net/m0_54158068/article/details/124372769