2013-01-06 115 views
5

我是C新手,並且在使用chdir()時遇到問題。我使用一個函數來獲取用戶輸入,然後從中創建一個文件夾並嘗試chdir()進入該文件夾並創建另外兩個文件。無論何時我嘗試通過查找器訪問文件夾(手動)我沒有權限。無論如何,這裏是我的代碼,任何提示?在C中更改工作目錄?

int newdata(void){ 
    //Declaring File Pointers 
    FILE*passwordFile; 
    FILE*usernameFile; 

    //Variables for 
    char accountType[MAX_LENGTH]; 
    char username[MAX_LENGTH]; 
    char password[MAX_LENGTH]; 

    //Getting data 
    printf("\nAccount Type: "); 
    scanf("%s", accountType); 
    printf("\nUsername: "); 
    scanf("%s", username); 
    printf("\nPassword: "); 
    scanf("%s", password); 

    //Writing data to files and corresponding directories 
    umask(0022); 
    mkdir(accountType); //Makes directory for account 
    printf("%d\n", *accountType); 
    int chdir(char *accountType); 
    if (chdir == 0){ 
     printf("Directory changed successfully.\n"); 
    }else{ 
     printf("Could not change directory.\n"); 
    } 

    //Writing password to file 
    passwordFile = fopen("password.txt", "w+"); 
    fputs(password, passwordFile); 
    printf("Password Saved \n"); 
    fclose(passwordFile); 

    //Writing username to file 
    usernameFile = fopen("username.txt", "w+"); 
    fputs(password, usernameFile); 
    printf("Password Saved \n"); 
    fclose(usernameFile); 

    return 0; 


} 
+1

這行很奇怪:'int chdir(char * accountType);' – lbonn

回答

5

其實你不變化的目錄,你只需要聲明一個函數原型爲chdir。然後您繼續比較該函數指針與零(與NULL相同),這就是失敗的原因。

您應該包括爲原型的頭文件<unistd.h>,然後居然呼叫功能:

if (chdir(accountType) == -1) 
{ 
    printf("Failed to change directory: %s\n", strerror(errno)); 
    return; /* No use continuing */ 
} 
+0

所以如果你不介意我問怎麼改成accountType目錄並創建代碼中的兩個文件?對不起,我剛接觸C. = /並感謝答案。 –

3
int chdir(char *accountType); 

不調用該函數,試試下面的代碼來代替:

mkdir(accountType); //Makes directory for account 
printf("%d\n", *accountType); 
if (chdir(accountType) == 0) { 
    printf("Directory changed successfully.\n"); 
}else{ 
    printf("Could not change directory.\n"); 
} 

另外,printf行看起來很可疑,我想你要的是打印accountType字符串:

printf("%s\n", accountType);