當前位置:首頁 > 公眾號精選 > 嵌入式云IOT技術(shù)圈
[導(dǎo)讀]設(shè)計一個API:?int?get_buf_data(char?*buf,char?*data)? 用于獲取文件中的數(shù)據(jù): #include #include #include #include #include int get_buf_data(char *buf,char *data) { char *p1 =NULL,* p2=NULL

設(shè)計一個API: int get_buf_data(char *buf,char *data) 

用于獲取文件中的數(shù)據(jù):

#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打開對應(yīng)的文件,通過讀取文件中的數(shù)據(jù)保存到buf中,然后,通過buf找到文件中對應(yīng)的字符串,讀取該字符串后面對應(yīng)的整形型數(shù)據(jù)并返回,當然,也可以設(shè)計成別的形式。

     這里主要是要熟悉strstr這個函數(shù),這個是字符串的查找函數(shù),上面這個API就是首先返回查找到對應(yīng)子串的首地址,然后返回給一個指針接受,后面用另一個指針加上獲得剛剛返回子串地址的偏移到達這個子串的首地址,再利用strlen計算這個子串的長度再與首地址相加即得到下一個串,再利用atoi將該串轉(zhuǎn)化為整型。

函數(shù)原型:

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

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

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

    返回值:若str2是str1的子串,則返回str2在str1的首次出現(xiàn)的地址;如果str2不是str1的子串,則返回NULL。

     
  


免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺僅提供信息存儲服務(wù)。文章僅代表作者個人觀點,不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!

本站聲明: 本文章由作者或相關(guān)機構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內(nèi)容真實性等。需要轉(zhuǎn)載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請及時聯(lián)系本站刪除。
關(guān)閉
關(guān)閉