我正在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);
}
}
关于chdir 在 c 代码下的 unix 中不起作用,总是无法更改目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996565/