#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()无法更改目录。为什么这样做以及可以采取哪些措施来解决它?
非常感谢:)
答案 0 :(得分:2)
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.
}