在C中更改工作目录?

时间:2013-01-06 05:19:39

标签: c chdir

我是C的新手,我在使用chdir()时遇到了麻烦。我使用一个函数来获取用户输入,然后我从中创建一个文件夹并尝试将chdir()放入该文件夹并再创建两个文件。当我尝试通过finder(手动)访问该文件夹时,我没有权限。无论如何这里是我的代码,任何提示?

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;


}

2 个答案:

答案 0 :(得分:5)

您实际上更改目录,您只需为chdir声明一个函数原型。然后,您继续将该函数指针与零(这与NULL相同)进行比较,这就是失败的原因。

您应该为原型包含头文件<unistd.h>,然后实际调用函数:

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

答案 1 :(得分: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行看起来很可疑,我想你想要的是print accountType string:

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