如果与 fgets() 一起使用,chdir() 不会更改目录

chdir() does not changes directory if used with fgets()

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>

int main()
{
    char temporaryPath[50];

    fgets(temporaryPath, sizeof(temporaryPath), stdin);

    if(chdir(temporaryPath) == -1)
        printf("Failed to change directory\n"); 

    getcwd(temporaryPath, 1000);
    printf("%s> ", temporaryPath);
}

我一直在搜索有关更改目录的大量信息,但一直无法弄清楚为什么 chdir() 在这种情况下会失败。如果我使用 fgets() 而不是对 temporaryPath 数组进行硬编码,chdir() 将无法更改目录。为什么会这样,可以做些什么来解决它?

非常感谢:)

if ( fgets(temporaryPath, sizeof(temporaryPath), stdin) != NULL )
{
   int len = strlen(temporaryPath);
   if ( temporaryPath[len-1] == '\n' )
   {
      temporaryPath[len-1] = '[=10=]';
   }

   // Now that the newline has been trimmed, use temporaryPath. 
}