2016-03-14 103 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