chdir在c代码下无法在unix中工作,总是无法更改目录

时间:2016-03-14 19:38:45

标签: c linux ftp

我正在使用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);
    }
}

1 个答案:

答案 0 :(得分:0)

您将不正确的尺寸传递给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);
    }
}