This question already has answers here:
Usage of fgets function in C
                                
                                    (7个答案)
                                
                        
                                4年前关闭。
            
                    
#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()而不是对临时路径数组进行硬编码,则chdir()无法更改目录。为什么会这样,该如何解决?

非常感谢你 :)

最佳答案

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

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

关于c - 如果与fgets()一起使用,chdir()不会更改目录。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29419702/

10-09 02:13