![](/img/trans.png)
[英]chdir(getenv(“HOME”) prompts error “No such file or directory”
[英]chdir() - no such file or directory
int main(int argc, char **argv)
{
char input[150];
char change[2] = "cd";
char *directory;
while(1) {
prompt();
fgets(input, 150, stdin);
if(strncmp(change, input, 2) == 0) {
directory = strtok(input, " ");
directory = strtok(NULL, " ");
printf(directory);
chdir(directory);
perror(directory);
}
if(feof(stdin) != 0 || input == NULL) {
printf("Auf Bald!\n");
exit(3);
}
}
}
當我開始這個並輸入“cd test”時,我得到“沒有這樣的文件或目錄”。 但是有一個目錄“test”。
在Arch Linux上運行。
從手冊頁 :
fgets()從流中讀取最多一個小於大小的字符,並將它們存儲到s指向的緩沖區中。 讀數在EOF或換行符后停止。 如果讀取換行符,則將其存儲到緩沖區中。
問題是你從fgets()
得到的字符串末尾有一個換行符'\\n'
,你需要刪除它:
fgets(input, 150, stdin);
input[strlen(input)-1] = '\0';
也:
char change[2] = "cd";
那應該是change[3]
,它是2(對於“cd”)+ 1為NULL終止符'\\0'
,它會自動為您放置。
然后它應該工作。
編輯 :
另一種方法是更改strtok()
調用,以便:
directory = strtok(NULL, " \n");
如果用戶通過回車鍵或通過EOF(Linux上的ctrl + d)字符輸入字符串,這將有效...我不確定第二個用戶可能會做多少...但它不能'傷害了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.