Search code examples
cfgets

C fgets() - Only last line of the file is written to array?


I have a really weird problem with fgets() in C. Below is the code I'm working with.

FILE* conf_file;
char array[20];
conf_file=fopen("configuration","r");
if (!conf_file) printf("There is not conf file");
while(!feof(conf_file)){
    // if( feof(conf_file)) break;
    fgets(array,20,conf_file);
    //printf("%s",array);
    if (!read_id_flag){
        labris_id=atoi(array);
        read_id_flag=1;
        printf("%d\n",id);
        continue;
    }
    protocol_array[protocol_index]=array;
    // printf("%s %s",array,protocol_array[protocol_index]);
    protocol_index++;
}
int i;
for(i=0;i<10;i++){
    printf("%s",protocol_array[i]);
}
fclose(conf_file);

Well, in the while scope if I try to print the protocol_array it works perfectly. But if I try to print the array after the while scope, it prints only the last line of the array, 6 times (6 is number of lines in the file).

Any idea is appreciated. Thanks in advance.


Solution

  • char* protocol_array[]; can't contain any data directly, other than a pointer to the allocated memory.

    You should either define protocol_array as char protocol_array[20][6];, allocating storage for 6 lines of string with length 20 and strcpy like this:

    char protocol_array[20][6];
    //...
    strcpy( protocol_array[protocol_index], array );
    

    or allocate the memory via malloc:

    char** protocol_array = malloc( 6 * sizeof( char* ) );
    //...
    protocol_array[protocol_index] = malloc( strlen(array)+1 );
    strcpy( protocol_array[protocol_index], array );
    

    Note that in the latter case you should free any allocated memory when you're done with it:

    for( i = 0; i<protocol_index; ++i )
        free( protocol_array[i] );
    free( protocol_array );