C语言: Search text file for a "var" and store the next string as the value

标签 c string search scanf fgets

我怎样才能完成以下任务:

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/

相关文章:

css - 双行导航栏 - 是什么原因造成的?

c - 无法循环工作

c - 函数内的自由字符指针

c - Fprintf 不将数组写入文件

c - 优化字符串指针数组

c++ - 将字符串从托管列表框拉到 char* 类型的类变量中

java - String.replace() 不工作

c - 如何在 execlp() 之后找到程序的返回值?

Azure 搜索 : Searching for singular version of a word, 但结果中仍包含复数版本

java - 使用方法在数组中搜索唯一名称