Hugo Novais
Hugo Novais

Reputation: 89

Function to compare different files

I've written a function that compares two different files and it prints if they're equal or not. The problem is that the files are the same and at some point it returns as FAILED.

This is the function that I have:

void comparar_conteudo(){

    for(int i = 1; i <= 10; i++){

        int bp = 0;
        char ficheiro1[100] = "saida/command";
        char ficheiro2[100] = "expected/exp_query";

        char commandString[2]; sprintf(commandString, "%d", i);

        strcat(ficheiro1, commandString); strcat(ficheiro2, commandString);
        strcat(ficheiro1, "_output.txt"); strcat(ficheiro2, ".txt");

        FILE *novoFile1 = fopen(ficheiro1, "r");
        FILE *novoFile2 = fopen(ficheiro2, "r");

        char* line1 = malloc(sizeof(char));
        char* line2 = malloc(sizeof(char));

        while(fgets(line1, 1024, novoFile1)){

            fgets(line2, 1024, novoFile2);

            if(strcmp(line2,line1) != 0){
                bp = 1;
                break;
            }
        }

        if(bp == 0)
            printf("Query %d: SUCCESS\n", i);

        else
            printf("Query %d: FAILED\n", i);

        fclose(novoFile1);
        fclose(novoFile2);
        free(line1);
        free(line2);
    }
}

The output looks like this:

Query 1: SUCCESS
Query 2: SUCCESS
Query 3: SUCCESS
Query 4: SUCCESS
Query 5: FAILURE
double free or corruption (out)
Aborted (core dumped)

I can't find the problem so I would be thankful if you could help me!

EDIT:

If I ask to print what both lines have it returns like this:

Query 1: SUCCESS
Query 2: SUCCESS
Query 3: SUCCESS
Query 4: SUCCESS
13108172;LeonardoCoelho71950;29

13108172;LeonardoCoelho71950;29
13108172;LeonardoCoelho71950;29

Query 5: FAILED
double free or corruption (out)
Aborted (core dumped)

Upvotes: 0

Views: 192

Answers (1)

pm100
pm100

Reputation: 50140

once you did this

    char* line1 = malloc(sizeof(char));
    char* line2 = malloc(sizeof(char));

    while(fgets(line1, 1024, novoFile1)){

all bets are off

you allocated line1 as one byte, then read 1024 bytes into it. At least

    char* line1 = malloc(1024);
    char* line2 = malloc(1024);

Upvotes: 2

Related Questions