我怎样才能完成以下任务:
file = fopen("filename","r");
search_word_int( "var1" , file , 1 );
search_word_int( "var2" , file , 1 );
...
fclose(file);
我用过:
int search_word_int( char *word , FILE *file , int *step )
{
char dummy[256];
int variable = 0, step_ = step;
while( (fgets( dummy , 256 , file )) != NULL )
{
if( strcmp( dummy , word ) != 0 )
{
for (int i = 0 ; i < step_ + 1 ; i++)
fscanf( file , "%d" , &variable );
printf("%s is found = %d\n",word,variable);
return(variable);
}
}
}
作为搜索函数,但fgets似乎并不从文件的开头开始搜索,而是在最后一次调用后继续获取下一行!
最佳答案
每个 FILE 都有一个文件位置或偏移量,当您执行 fgets() 时,该位置会向前移动。如果您希望从文件开头读取,请在 search_word_int() 函数的开头插入以下行,以将文件偏移量移动到文件开头:
fseek(file, 0, SEEK_SET);
关于C语言: Search text file for a "var" and store the next string as the value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745256/