Char problem * and fgets()

Asked

Viewed 248 times

1

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

text 1
text2
text 3
text4

I need to read the entire file row by row and store each row in a vector position of struct. I made this code here, but it stores the last line in all the positions of this vector 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?

1 answer

1

The problem is on this line:

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

Here you are doing two things:

  1. Overwriting the a every line read

  2. Pointing all vectors to a

This way, when iterating the vectors, you 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 to the item of the vector in the fgets, as in this example:

struct musica2{
   char musica[255];
};

...

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

See working on IDEONE.

I was just trying to figure out the main problem. Then you need to put the proper protections to check the fgets return, and ensure that the string is properly formatted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.