chdir 在 c 代码下的 unix 中不起作用,总是无法更改目录

标签 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);
    }
}

最佳答案

您向 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/

相关文章:

c - 多维数组行为异常

c++ - 性能比较:strstr() 与 std::string::find()

c - 重用 ANTLR3 词法分析器和解析器

java - 如何使用 Apache Commons Net 写入远程文件?

macos - Windows Azure 和 FileZilla FTP

c - 列出 C 程序中的所有 #defines

linux - 项目错误QT

python - Flask api 从 python shell 运行,但在 Ubuntu 上托管后不运行

linux - 带有 freerdp 非事件超时的远程桌面

ssh - wordmove 验证 movefile 部分 : production error This remote has not ssh nor ftp protocol defined