Strtok字符串并将其传递给另一个函数

时间:2011-11-09 00:09:02

标签: c strtok

我发现strtok函数在将相同的字符串传递给另一个函数时有一些技巧,代码如下:

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

void split_redirect(char input[80], int switch_bit);
void split_background(char *split_cmd);

void split_background(char *split_cmd){

    char *tmp = strchr(split_cmd, '&');
    if (tmp == NULL){ }
    else{
        char *command = strtok(split_cmd,"&");        
        while(command!=NULL){        
            // char *command_next = strtok(NULL,"&");
            printf("command=[%s]\n",command);

            if((strchr(command,'>')!=NULL)||(strchr(command,'<')!=NULL)){ 
                split_redirect(command,0);             
            }
            // command = command_next;
            command = strtok(NULL,"&");
            printf("command_next=[%s]\n",command);     
         }
    }
}

void split_redirect(char input[80], int switch_bit){
     char *tmp ,*tmp2;
     tmp = strchr(input, '>');
     tmp2 = strchr(input, '<');

     if (tmp == NULL && tmp2 == NULL){  }
     else if(tmp2 == NULL && tmp !=NULL){
     // single > 
        char *copy = (char *)malloc(sizeof(input));
        strcpy(copy,input);
        char *tmp = strtok(copy,">");
        char *cmd = tmp;
        tmp = strtok(NULL,"\0");

        if (strchr(tmp,'>')==NULL){
           char *file_name = strtok(tmp," ");
        }
        else{
           free(copy);
           copy=NULL;            
        }
    }
    else{ }
}

void main(int argc,char *argv[]){
    // char *cmd2 = "cmd1 > txt & cmd2 > txt2" // -> each char can't be change, so strotk this string will get seg fault. Modify token to '\0' is illegal. in .RDATA
    char cmd[80] = "cmd1 > txt & cmd2 > txt &"; 
    split_background(cmd);  
}


Expect output:
command=[cmd1 > txt ]
command_next=[ cmd2 > txt ]

The output:
command=[cmd1 > txt ]
command_next=[(null)]

为什么当我将此字符串传递给另一个函数时,会导致其余字符串变为空字符串?当我取消标记char *command_next = strtok(NULL,"&");并将command = strtok(NULL,"&");替换为command = command_next;时,它将打印其余的字符串作为我的期望。它与strtok如何通过静态存储器存储该字符串有关吗?

1 个答案:

答案 0 :(得分:2)

阅读the manualstrtok函数更改原始字符串,并用空字节覆盖分隔符字符。字符串的其余部分不会“变为空字符串”,但您必须在最后找到的标记之后恢复字符串的其余部分。

最好是惯用strtok来提取所有标记,然后单独处理这些标记。

相关问题