简体   繁体   中英

C strncat to my environment

So I got my go to split the environment path and I got them all

char *token;
char *path;
char copy[200];
char *search = ":";
char echo[] = "echo";
int main(){

    path= getenv("PATH");
    strncpy(copy,path,sizeof(copy)-1);

    token = strtok (copy,":");
    printf("%s\n",path);
    while(token != NULL)
    {
        printf("%s\n",token);
        token= strtok (NULL,":");
    }
}

I get want I need

/usr/lib64/qt-3.3/bin
/usr/NX/bin
/usr/local/bin
/usr/bin
/usr/divms/bin
/usr/local/sbin
/usr/sbin
/space/befox/bin
/space/befox/bin

now I just need to concat a "/" to the end of all of those, and i got it to work BUT it only prints the 1st one. so here is my code:

char *token;
char *path;
char copy[200];
char *search = ":";
char echo[] = "echo";
char *result;
int main(){

    path= getenv("PATH");
    strncpy(copy,path,sizeof(copy)-1);

    token = strtok (copy,":");
    printf("%s\n",path);
    while(token != NULL)
    {
        result = strncat (token,"/",sizeof(token+1));
        printf("%s\n",token);
        token= strtok (NULL,":");
    }
}

and now I just get:

/usr/lib64/qt-3.3/bin/

What do I need to fix so I get all of the lines with a "/" at the end of them?

You can't modify the values that strtok returns. You're lengthening them by 1 char, which means you're writing past the end of a string, which is undefined behavior. In all likelihood, strtok replaces the : with a \\0 and saves a pointer to just past the \\0 , which should be the beginning of your second token. However, you replace that \\0 with a / and put a \\0 just past that point, and now when strtok goes to look for your next token, all it finds is that \\0 and it assumes your string is done.

Don't modify the return value from strtok without copying it first.

I you just want to print, you might want to add the / in the format line:

printf("%s/\n",token);

You are getting only one line because you are modifying the buffer you are reading with the following line:

strncat(token, "/", sizeof(token+1));

As per documentation:

Appends the first num characters of source to destination, plus a terminating null-character.

You should copy the token and then add the trailing / .

You shouldn't attempt to modify the string you're passing to strtok() , you'll get highly unexpected behavior that way. You should set up a new string and copy the string pointed to by token to it, and do the concatenation there. sizeof(token+1) is also incorrect, both because you're just adding 1 to the pointer and not affecting the result of sizeof at all, and because you're just getting the size of the pointer this way. strlen() is what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM