读取文件,但仅在文件中插入最后一个字符串

时间:2018-09-18 02:23:47

标签: c debugging segmentation-fault

我正在读取3个文件并将它们合并到一个称为mergedfile的数组中,但是当我尝试打印该数组时,它只会打印出第一个文件中的最后一个单词。不知道如果有人知道可能是什么问题,我是否会错误地读取文件或将字符串错误地放入数组中,我将不胜感激。谢谢。 美国文件包含我需要按字母顺序排序的字符串,并将其插入word.txt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main()
{

    //open three files for merging
    FILE *fp1 = fopen("american0.txt","r");
    FILE *fp2 = fopen("american1.txt","r");
    FILE *fp3 = fopen("american2.txt","r");



    //open file to store the result
    FILE *fpm = fopen("words.txt", "w");



    //creating an array to save the files data
    char temp[50];
    char *(*mergedFile);
    //creating variables for while and if loops
    int i =0, j=0;
    int count=0;
    char *p;
    int q=0;
    int z = 0;



    //checking to make sure files are being read

    if(fp1 == NULL || fp2 == NULL || fp3 == NULL)
    {
        printf("Could not open one or all of the files.\n");
        printf("Exiting program!");
        exit(0);
    }




    //reading the data from files

    while (fgets(temp, 50 ,fp1) != NULL)
    {
        count++;
    }
    fclose(fp1);
    while (fgets(temp, 50 ,fp2) != NULL)
    {

        count++;
    }
    fclose(fp2);
    while (fgets(temp, 50 ,fp3) != NULL)
    {

        count++;
    }
    fclose(fp3);




    //inserting data into the array
    mergedFile = (char **)malloc(sizeof(char*) *count);
    for(int i=0; i<count; i++){
        mergedFile[i]=(char*)malloc(sizeof(char)*50);

    }
    fp1 = fopen("american0.txt","r");
    fp2 = fopen("american1.txt","r");
    fp3 = fopen("american2.txt","r");

    if(fp1 == NULL || fp2 == NULL || fp3 == NULL )
    {
        printf("Could not open one or all of the files.\n");
        printf("Exiting program!");
        exit(0);
    }
    i=0;

    while (fgets(temp, 50, fp1) != NULL)
    {
         mergedFile[i++]= temp;     
    }

    while (fgets(temp, 50, fp2) != NULL)
    {
         mergedFile[i++]= temp;     
    }

    while (fgets(temp, 50, fp3) != NULL)
    {
         mergedFile[i++]= temp;     
    }
    for(z = 0; z <count; z++)
    printf("%s", mergedFile[z]);




    /*
    //sorting the array alphabetically
    for(i=1; i<count; i++)
    {
        for(j=1; j<count;j++)
        {
            if(strcmp(mergedFile[j-1], mergedFile[j]) > 0)
            {
                strcpy(temp, mergedFile[j-1]);
                strcpy(mergedFile[j-1], mergedFile[j]);
                strcpy(mergedFile[j], temp);
            }
        }
    }
    */

    //next goal is to print the array to file word.txt



    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    //fclose(fpm);


    return 0;

}

1 个答案:

答案 0 :(得分:1)

每次执行fgets时,都会覆盖temp

此外,mergedFile中的所有条目都被赋予指向temp的[same]指针值。

因此,所有条目都将以第三个文件的 last 行的值结尾。

您需要为每行保存一个单独的副本。因此,请全部更改:

mergedFile[i++]= temp;

进入:

mergedFile[i++]= strdup(temp);