您的位置:首頁>正文

shell腳本調用C語言之字串切分函數——strtok

今天上午在寫一個需求, 要求的比較急, 要求當天完成, 我大致分析了一下, 可以採用從shell腳本中插入一連串的日期, 通過調用proc生成的可執行檔, 將日期傳入後臺資料庫, 在資料庫中進行計算。 需要切分日期的字串, 轉化成整數, 插入int 陣列中, 手工實現太慢, 就直接借用系統的strtok函數來用了。

場景模擬:

1. shell腳本:

#diao.sh #!/bin/bash date1="20170622,20170623,20170626,20170627,20170628,20170629,20170627" date2="20170628,20170629,20170630" if [ $1 -eq 0 ] then compute $date1 else compute $date2 ~

2. 後臺proc代碼, 這裡用C代碼來模擬, 重點講述用strtok函數實現字串的切分。

#include #include #include int main(int argv ,char * argc[]) { char buf[100]; char * p = NULL; char buf2[100][9]; int data[100]; int len = 0; int i = 0; memset(buf,0x00,sizeof(buf)); memset(buf2,0x00,sizeof(buf2)); memset(data,0x00,sizeof(data)); memcpy(buf,argc[1],strlen(argc[1])); printf("buf=%s ",buf); /* 下面代碼按照","切分字串, 然後轉化成整數, 存入整數陣列中*/ p = strtok(buf, ","); while( p!= NULL){ strcpy(buf2[len],p); data[len] = atoi(buf2[len]); printf("buf2[%d]=%s ",len,buf2[len]); len++; p = strtok(NULL, ","); // 再次調用strtok函數 } /* 上面的代碼按照","切分字串, 然後轉化成整數, 存入整數陣列中*/
for ( i = 0 ; i

編譯運行情況:

思考:將上述代碼中字串切割, 並轉化為整數, 存入整數陣列部分做成一個獨立的函數, 進行調用, 通用性一下子就上來了。

3. 將切分過程做成一個獨立的函數

函數名稱為:mystrtok, 裡面還是調用系統的strtok,如果直接用系統的strtok不做任何處理, 是試用不了的,

因為strtok出來的都是char*類型的。

#include #include #include int mystrtok(char * str,const char * delim, char buf[][9],int * len, int data[]) { char * p = NULL; int i = 0; p = strtok(str, delim); while( p!= NULL){ strcpy(buf[i],p); data[i] = atoi(buf[i]); i++; p = strtok(NULL, delim); // 再次調用strtok函數 } *len = i; return 0; } int main(int argv ,char * argc[]) { char buf[100]; char * p = NULL; char buf2[100][9]; int data[100]; int len = 0; int i = 0; memset(buf,0x00,sizeof(buf)); memset(buf2,0x00,sizeof(buf2)); memset(data,0x00,sizeof(data)); memcpy(buf,argc[1],strlen(argc[1])); printf("buf=%s ",buf); /* 下面代碼按照","切分字串, 然後轉化成整數, 存入整數陣列中*/ /* p = strtok(buf, ","); while( p!= NULL){ strcpy(buf2[len],p); data[len] = atoi(buf2[len]); printf("buf2[%d]=%s ",len,buf2[len]); len++; p = strtok(NULL, ","); // 再次調用strtok函數 } */ /* 上面的代碼按照","切分字串, 然後轉化成整數, 存入整數陣列中*/ /* 思考, 將上述代碼寫成一個獨立的函數, 進行調用*/ mystrtok(buf,",",buf2,&len,data); for ( i = 0 ; i

運行新的代碼:

上述函數可以在任何字串切割的場景中用到, 尤其是數位字串按照某種方式切割時。

另外一個值得注意的地方就是:shell腳本調用C程式時, main函數的參數中接受到shell腳本的參數, 然後進行處理。

特別是字串類型 char * , 字元陣列 char buf, 字元陣列指標 char *p, const char * 這些類型一定要搞清楚, 之間是否可以轉, 怎麼轉,

互相之間如何賦值的, 都要非常清楚。

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示