2013-01-06 78 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);