首页 > 编程语言 > 详细

C语言读取文件中字符串

时间:2020-12-16 15:21:47      阅读:23      评论:0      收藏:0      [点我收藏+]
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

 

C语言读取文件中字符串

原文:https://www.cnblogs.com/birdBull/p/14143362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!