简体   繁体   English

C fgets()-仅将文件的最后一行写入数组?

[英]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. 我在C语言中的fgets()有一个很奇怪的问题。以下是我正在使用的代码。

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. 好吧,在while范围内,如果我尝试打印protocol_array它会完美地工作。 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). 但是,如果我尝试在while范围之后打印数组,它将仅打印数组的最后一行,共6次(6是文件中的行数)。

Any idea is appreciated. 任何想法表示赞赏。 Thanks in advance. 提前致谢。

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]; 您应该将protocol_array定义为char protocol_array[20][6]; , allocating storage for 6 lines of string with length 20 and strcpy like this: ,为长度为20和strcpy的6行字符串分配存储,如下所示:

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

or allocate the memory via malloc : 或通过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: 请注意,在后一种情况下,完成后应free所有分配的内存:

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

protocol_array[protocol_index]=array; protocol_array [protocol_index] = array; - This line seems to be the problem. -这行似乎是问题所在。 You should do a strcpy. 您应该做一个strcpy。

If you keep assigning, array each time, only the address of array (which is a local array) gets stored in all the elements of protocol_array. 如果您每次都继续分配array,则只有array(本地数组)的地址存储在protocol_array的所有元素中。 As evident from your code, the last read line will be present in the "array" and since all elements of protocol_array points to address of "array", it just prints that for all elements. 从您的代码可以明显看出,最后读取的行将出现在“数组”中,并且由于protocol_array的所有元素都指向“数组”的地址,因此它仅对所有元素进行打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM