2016-03-14 100 views
-1

我正在unix下C下的ftp服务器上工作,我在实现change工作目录功能时遇到了困难,我已经有<unistd.h>包括你认为的问题是什么是什么?chdir不工作在unix下的c代码总是无法更改目录

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

回答

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); 
    } 
} 
+0

你好谢谢对于你的回复,getcwd()与这种方式的大小在另一个函数 – Ayman

+0

中运行良好,但在我的代码中它甚至没有进入该区域cz chdir总是给出!= 0 – Ayman

+0

@Ayman:'space'可能被定义为数组中的其他函数。关于当前的问题,printf(“cmdline:%s \ n”,cmdline);'? – chqrlie