Problem with char * and fgets ()

1

I have struct with a field of type vector of char and I have a file .txt with several lines in this format with names of songs.

  

text1
text2
text3
text4

I need to read the entire file line by line and store each line in a position of the struct vector. I made this code here, but it stores the last line in all positions of the vector of that struct .

    #include <iostream>
    #include <cstring>
    #include <fstream>

    using namespace std;

    struct musica2{
       char *musica;
    };

    int main(){
       FILE *arquivo;
       musica2 *z = new musica2[12];
       char a[255];
       arquivo = fopen("teste.dat", "r");
       int i=0;
       if(arquivo == NULL)
           cout << "Erro ao abrir arquivo." << endl;
       else{
        while(!feof(arquivo)){
        z[i].musica = fgets(a,255,arquivo);
        i++;
       }
      }
    cout << z[3].musica;
    fclose(arquivo);
    return 0;
    } 

What can it be?

    
asked by anonymous 20.06.2014 / 06:29

1 answer

1

The problem lies in this line:

z[i].musica = fgets(a,255,arquivo);

Here you are doing two things:

  • Overwriting a for each line read

  • Pointing all vectors to a

  • In this way, iterating the vectors will have the same return for all.

    The solution would be to copy the value of a to the vector, or to eliminate the a completely point directly the vector item in fgets , as in this example:

    struct musica2{
       char musica[255];
    };
    
    ...
    
    fgets( z[i].musica, 255, arquivo);
    

    See working at IDEONE .

      

    I just looked at the main problem. Then you need to put the proper protections to check the return of fgets, and ensure that the string is properly formatted.

        
    20.06.2014 / 07:59