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

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

場景模擬:數據庫

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
fi                             

2. 後臺proc代碼,這裏用C代碼來模擬

重點講述用strtok函數實現字符串的切分。數組

 

#include<string.h>
#include<stdlib.h>
#include<stdio.h>

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\n",buf);
 /* 下面代碼按照","切分字符串,而後轉化成整數,存入整數數組中*/
   p = strtok(buf, ",");              
  while( p!= NULL){  
        strcpy(buf2[len],p);
        data[len] = atoi(buf2[len]);         
        printf("buf2[%d]=%s\n",len,buf2[len]);
        len++;
        p = strtok(NULL, ",");          // 再次調用strtok函數  
    } 
  /* 上面的代碼按照","切分字符串,而後轉化成整數,存入整數數組中*/

for ( i = 0 ; i < len ; ++i){ printf ("data[%d]=%d\n",i,data[i]); } }

編譯運行狀況:bash

 思考:將上述代碼中字符串切割,並轉化爲整數,存入整數數組部分作成一個獨立的函數,進行調用,通用性一會兒就上來了。函數

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

函數名稱爲:mystrtok,裏面仍是調用系統的strtok,若是直接用系統的strtok不作任何處理,是試用不了的,由於strtok出來的都是char*類型的。spa

#include<string.h>
#include<stdlib.h>
#include<stdio.h>
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\n",buf);  
 /* 下面代碼按照","切分字符串,而後轉化成整數,存入整數數組中*/
/*   p = strtok(buf, ",");              
  while( p!= NULL){  
        strcpy(buf2[len],p);
        data[len] = atoi(buf2[len]);         
        printf("buf2[%d]=%s\n",len,buf2[len]);
        len++;
        p = strtok(NULL, ",");          // 再次調用strtok函數  
    } */ 
  /* 上面的代碼按照","切分字符串,而後轉化成整數,存入整數數組中*/ 
  /* 思考,將上述代碼寫成一個獨立的函數,進行調用*/
  mystrtok(buf,",",buf2,&len,data); 
  for ( i = 0 ; i < len ; ++i){
      printf ("data[%d]=%d\n",i,data[i]);
   }
  
   
}

運行新的代碼:指針

上述函數能夠在任何字符串切割的場景中用到,尤爲是數字字符串按照某種方式切割時。code

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

特別是字符串類型 char * ,字符數組 char buf[][],字符數組指針 char *p[], const char * 這些類型必定要搞清楚,之間是否能夠轉,怎麼轉,字符串

互相之間如何賦值的,都要很是清楚。

相關文章
相關標籤/搜索