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<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]);
  }

}

编译运行情况:

 思考:将上述代码中字符串切割,并转化为整数,存入整数数组部分做成一个独立的函数,进行调用,通用性一下子就上来了。

3. 将切分过程做成一个独立的函数

函数名称为:mystrtok,里面还是调用系统的strtok,如果直接用系统的strtok不做任何处理,是试用不了的,因为strtok出来的都是char*类型的。

#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]);
   }
  
   
}

运行新的代码:

上述函数可以在任何字符串切割的场景中用到,尤其是数字字符串按照某种方式切割时。

另外一个值得注意的地方就是:shell脚本调用C程��时,main函数的参数中接受到shell脚本的参数,然后进行处理。

特别是字符串类型 char * ,字符数组 char buf[][],字符数组指针 char *p[], const char * 这些类型一定要搞清楚,之间是否可以转,怎么转,互相之间如何赋值的,都要非常清楚。

猜你喜欢

转载自www.linuxidc.com/Linux/2017-06/144899.htm