首页 > 解决方案 > 为什么我不能合并两个文件并将内容存储到 C 中的另一个文件

问题描述

void mergeFile(){
    //allocate memory
    char * firFile = (char*) malloc(MAX_SIZE);
    char * secFile = (char*) malloc(MAX_SIZE);
    char * conFile = (char*) malloc(MAX_SIZE);
    char * buffer = (char*) malloc(MAX_SIZE);
    char ch;
    
    // get name of first file
    printf("Enter name of first file: ");
    __fpurge(stdin);
    gets(buffer);
    strcpy(firFile, FOLDER);
    strcat(firFile, buffer);
    
    //get name of second file
    printf("Enter name of second file: ");
    __fpurge(stdin);
    gets(buffer);
    strcpy(secFile, FOLDER);
    strcat(secFile, buffer);
    
    //get name of file will store
    printf("Enter name of file which will store contents of two files : ");
    __fpurge(stdin);
    gets(buffer);
    strcpy(conFile, FOLDER);
    strcat(conFile, buffer);

    //open 3 file with 'r' and 'w' mode
    FILE * firPtr = fopen(firFile,"r");
    FILE * secPtr = fopen(secFile, "r");
    FILE * conPtr = fopen(conFile, "w");
    
    //check 3 file NULL or not
    if (firPtr == NULL) {
        printf("Can not open %s file\n", firFile);
        remove(conFile);
    } else if (secPtr == NULL) {
        printf("Can not open %s file\n", secFile);
        remove(conFile);
    } else if (conPtr == NULL){
        printf("Can not open %s file\n",conFile);
    }else{
        // write all character in first file to file will store
        // MAY NOT WORK
        while ((ch = fgetc(firPtr)) != EOF)
            fprintf(conPtr, "%c", ch);
        
         // write all character in second file to file will store
         // MAY NOT WORK
        while ((ch = fgetc(secPtr)) != EOF)
            fprintf(conPtr, "%c", ch);
        printf("Two file were merged into %s file successfully\n!",conFile);
    }
    
    //clear all
    free(buffer);
    free(firFile);
    free(secFile);
    free(conFile);
    fclose(firPtr);
    fclose(secPtr);
    fclose(conPtr);
}

我用来fget从文件中获取字符并写入另一个文件,当我使用两个文件时我工作得很好,一个用于读取,一个用于存储,但是当我尝试将两个文件合并到另一个文件时,这段代码不起作用,不里面的东西包含文件。我在 Netbeans 8.2 中运行这段代码,你能从这段代码中给我错误吗,非常感谢!

标签: cfile

解决方案


推荐阅读