Changing working directories in Linux shell in a C program

后端 未结 2 1933
走了就别回头了
走了就别回头了 2020-12-12 03:34

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() f

相关标签:
2条回答
  • 2020-12-12 03:53

    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>
    
    0 讨论(0)
  • 2020-12-12 04:05

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

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

    0 讨论(0)
提交回复
热议问题