yaegerbomb
yaegerbomb

Reputation: 1178

Changing working directories in Linux shell in a C program

My goal is to write a C program that is like a basic shell for Linux. I have everything working except changing working directories. I have tried the system() for input strings for cd and nothing happened. I also tried chdir("tokened string") and also no luck. Anyone have any ideas? This is part of my code:

        fgets(cmdStr, sizeof(cmdStr), stdin);

        if( strncmp("quit", cmdStr, 4) == 0 || strncmp("Quit", cmdStr, 4) == 0  )
        {
            break;
        }
        else if( strncmp("cd", cmdStr, 2) == 0 )
        {
            char *token = strtok(cmdStr, " ");
            token = strtok(NULL, " ");
            chdir(token);
        }
        else
        {
            system(cmdStr);
        }
    }

Is it possible to do this? Or is this a simple case of something to do with the child shell not being able to do certain things?

Edit: Code above is complete.

Upvotes: 1

Views: 6362

Answers (2)

hari
hari

Reputation: 9733

Your chdir call is failing with -1 return value.

Please try to print the errno like this:

errno = 0;
chdir(token);
if ( errno != 0 ) {
    printf( "Error changing dir: %s\n", strerror( errno ) );
}

Keith is correct: \n at the end is killing you.

You can do following to get rid of it:

char *ptr = cmdStr;
<snip>
    else if( strncmp("cd", cmdStr, 2) == 0 )
    {
            strsep(&ptr, " ");       /* skip "cd"   */
            char *chr = strsep(&ptr, "\n");   /* skip "\n"  */
            errno = 0;
            chdir(chr);
            if ( errno != 0 )
               printf( "Error changing dir: %s\n", strerror( errno ) );
    }
</snip>

Upvotes: 2

Keith Thompson
Keith Thompson

Reputation: 263177

fgets() leaves the trailing '\n' character in cmdstr.

If you type cd foo, you'll call chdir("foo\n") rather than chdir("foo").

Upvotes: 5

Related Questions