C语言读取文件中字符串

int get_key_value(char* path, char* key_str, int* val)
{
    FILE *fp;

    if((fp = fopen(path, "r+")) == NULL)
    {
        perror("open");
        return -1;
    }
    
    long file_len;
    fseek(fp, 0, SEEK_END);     // 将文件指针移动到文件结尾,成功返回0,不成功返回-1
    file_len = ftell(fp);       // 求出当前文件指针距离文件开始的字节数
    fseek(fp, 0, SEEK_SET);     // 再定位指针到文件头

    char *str_buf = (char *)malloc(file_len + 1);
    while(fgets(str_buf, file_len, fp))   //循环读取每一行内容,直到文件结束
    {
        if(strstr(str_buf, key_str) != NULL)
        {
            int index= strlen(key_str);
            *val = atoi(&str_buf[index+1]);
        printf("value = %d\n", *val); free(str_buf); fclose(fp); return 1; } } free(str_buf); fclose(fp); return -2; }

 

文件内容 test.txt

hello

ID=234

SDFAOW

TEMP=988

 

 

调用   

  int val = 0;

 get_key_value("test.txt", "ID", &val);

运行结果

value = 234

 

posted @ 2020-12-16 13:26  小小小p鱼  阅读(2454)  评论(0编辑  收藏  举报