[英]Is using chdir() the only way to change the working directory in Linux C?
[英]chdir not working in unix under c code always failing to change directory
我正在使用 unix 下的 C 語言處理 ftp 服務器,我在實現更改工作目錄功能時遇到問題,我已經包含<unistd.h>
你認為問題是什么?
static int cwd(int ctrlfd, char *cmdline) {
printf("cmdline:%s\n", cmdline);
char *space = strtok(cmdline, " \n");
printf("cwd to :%s\n", cmdline);
if (chdir(space) == 0) {
getcwd(space, sizeof(space));
printf("changing directory successful %s\n", space);
return ftp_send_resp(ctrlfd, 250);
} else {
printf("changing directory failed\n");
return ftp_send_resp(ctrlfd, 550);
}
}
您將錯誤的大小傳遞給getcwd
:
getcwd(space, sizeof(space))
space
是一個指針, sizeof 不是緩沖區的大小,只是指針的大小。
從評論中的討論中編輯,如果成功,請嘗試修改您的函數以使用適當的緩沖區來讀取新的當前目錄,並在失敗時生成更多信息:
#include <errno.h>
static int cwd(int ctrlfd, char *cmdline) {
printf("cmdline:%s\n", cmdline);
char temp[200];
/* skip initial whitespace and cut argument on whitespace if any */
char *space = strtok(cmdline, " \n");
printf("cwd to :%s\n", cmdline);
if (chdir(space) == 0) {
getcwd(temp, sizeof(temp));
printf("changing directory successful: %s\n", temp);
return ftp_send_resp(ctrlfd, 250);
} else {
printf("changing directory to '%s' failed: %s\n",
space, strerror(errno));
return ftp_send_resp(ctrlfd, 550);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.