查看原文
其他

利用strstr与atoi的结合实现一个C语言获取文件中数据的工具

杨源鑫 嵌入式云IOT技术圈 2021-01-31

设计一个API: int get_buf_data(char *buf,char *data) 

用于获取文件中的数据:

#include <stdio.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int get_buf_data(char *buf,char *data) { char *p1 =NULL,* p2=NULL; int num =0; p1 = buf; p2 = strstr(p1,data); if(p2 == NULL) { printf("%s no find %s --- %s\r\n",__FUNCTION__ ,buf,data); return 0; } p1 = p2+strlen(data); num = atoi(p1); return num; } int main(void) { int fd = -1 ; char buf[1024]; fd = open("build_mtk8127eng.sh",O_RDWR); if(-1 == fd) { printf("open fair!\n"); return -1 ; } memset(buf,0,sizeof(buf)); read(fd,buf,1024); close(fd); int num = get_buf_data(buf,"student_num:"); printf("num:%d\n",num); return 0 ; }

     这个程序的作用就是,open打开对应的文件,通过读取文件中的数据保存到buf中,然后,通过buf找到文件中对应的字符串,读取该字符串后面对应的整形型数据并返回,当然,也可以设计成别的形式。

     这里主要是要熟悉strstr这个函数,这个是字符串的查找函数,上面这个API就是首先返回查找到对应子串的首地址,然后返回给一个指针接受,后面用另一个指针加上获得刚刚返回子串地址的偏移到达这个子串的首地址,再利用strlen计算这个子串的长度再与首地址相加即得到下一个串,再利用atoi将该串转化为整型。

函数原型:

extern char *strstr(char *str1, const char *str2);

    str1: 被查找目标 string expression to search.

    str2: 要查找对象 The string expression to find.

    返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。

     
  


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存