利用strstr與atoi的結(jié)合實(shí)現(xiàn)一個(gè)C語言獲取文件中數(shù)據(jù)的工具
掃描二維碼
隨時(shí)隨地手機(jī)看文章
設(shè)計(jì)一個(gè)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 ;
}
這個(gè)程序的作用就是,open打開對(duì)應(yīng)的文件,通過讀取文件中的數(shù)據(jù)保存到buf中,然后,通過buf找到文件中對(duì)應(yīng)的字符串,讀取該字符串后面對(duì)應(yīng)的整形型數(shù)據(jù)并返回,當(dāng)然,也可以設(shè)計(jì)成別的形式。
這里主要是要熟悉strstr這個(gè)函數(shù),這個(gè)是字符串的查找函數(shù),上面這個(gè)API就是首先返回查找到對(duì)應(yīng)子串的首地址,然后返回給一個(gè)指針接受,后面用另一個(gè)指針加上獲得剛剛返回子串地址的偏移到達(dá)這個(gè)子串的首地址,再利用strlen計(jì)算這個(gè)子串的長(zhǎng)度再與首地址相加即得到下一個(gè)串,再利用atoi將該串轉(zhuǎn)化為整型。
函數(shù)原型:
extern char *strstr(char *str1, const char *str2);
str1: 被查找目標(biāo) string expression to search.
str2: 要查找對(duì)象 The string expression to find.
返回值:若str2是str1的子串,則返回str2在str1的首次出現(xiàn)的地址;如果str2不是str1的子串,則返回NULL。
免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。文章僅代表作者個(gè)人觀點(diǎn),不代表本平臺(tái)立場(chǎng),如有問題,請(qǐng)聯(lián)系我們,謝謝!





