Search code examples
cfgetsstdio

fgets is getting only the last line of my file


i'm trying to write a code that inverts the lines of a file, something like this:

Original file:

aaa
bbb
ccc

Output file should be:

ccc
bbb
aaa

but , actualy the output file is like this:

ccc
ccc
ccc

i cant understand why. here is my code:

#include <stdio.h>
int main(){
    char linha[500];
    char *linhas[100];
    int flag = 0;
    FILE *texto,*invertido;
    // populando o vetor
    for(flag =0;flag < 100;flag++)
        linhas[flag] = linha;

    texto = fopen("texto.txt","r");
    if(texto == NULL)
        return 0;
    rewind(texto);
    for(flag = 0;fgets(linhas[flag],500,texto)!=NULL;flag++);

    flag--;
    invertido = fopen("invertido.txt","w");

    if(invertido == NULL)
        return 0;

    for(;flag >= 0;flag--)
        fprintf(invertido,"%d - %s\n",flag,linhas[flag]);

    fclose(invertido);
    fclose(texto);
    return 0;
}

Solution

  • When you do

    linhas[flag] = linha;
    

    you make all pointers in linhas point to the exact same place. So in the reading loop all lines you read will overwrite what was previously in the single buffer pointer to by linhas[flag].

    There are two possible solutions:

    1. Use an array of arrays, like in

      char linhas[100][500];
      
    2. Allocate each entry in linhas dynamically:

      for(flag =0;flag < 100;flag++)
          linhas[flag] = malloc(500);