简体   繁体   中英

Making a shell in C, but can't get chdir to work?

I'm writing a shell in C that's supposed implement several commands, one of them being the change directory command. To change directories, I use chdir(), but every time I run my code, I get a segmentation fault (core dumped) error. Here's my code:

.....
........
char *shell;
while((shell=readline("shell> ") )){
char *cmd = strtok(shell," ");

if(strcmp(cmd,"ls")==0)
 {
    //do something
 }
 else if(strcmp(cmd,"print")==0)
 {
   //do something
 }
else if(strcmp(cmd,"cd")==0){

            char *directory = strtok(NULL," ");

            if(chdir(directory)==-1){
                printf("Error\n");
            }
            else
            {
                printf("changed directories!");
            }


        }
      add_history(shell);
 }

I think I might be using strtok incorrectly?

Any help is appreciated, thank you :)

This

    char *directory = strtok(cmd," ");

should be

        char *directory = strtok(NULL," ");

When you call strtok() to get the next token, you pass NULL to it.

Moreover, strtok() is not re-entrant. So you can't use it even if your plan was to tokenize a different string. You can use strtok_r() on POSIX systems.

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