Search code examples
c++filefgets

I have an issue with fgets in c++


Im doing a small exercise to read a file which contains one long string and load this into an array of strings. So far I have:

char* data[11];
char buf[15];
int i = 0;

FILE* indata; 
indata = fopen( "somefile.txt", "r" );
while( i < 11)
{
    fgets(buf, 16, indata);
    data[i] =  buf;
    i++;
}

fclose( indata );

somefile.txt: "aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbaahhhhhbbbbdddddddddddddbbbbb"

etc..

This reads in 15 characters, adds that string to the array and gets the next 15. The problem is the array always equals the last string, so if the last string is "ccccv" the whole array, data[0] = "ccccv", data[1] = "ccccv", data[2] = "ccccv" and so on.

Does anyone know why this is happening and whether there is a better way to do it? Thanks


Solution

  • Each pointer in data will point to the same memory area, which is buf. You need to use strcpy + malloc.

    Also is seems like you have a "minor" buffer overflow. buf is size 15 and you're reading 16 characters.