Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中更改工作目录?_C_Chdir - Fatal编程技术网

在C中更改工作目录?

在C中更改工作目录?,c,chdir,C,Chdir,我是C新手,在使用chdir()时遇到问题。我使用一个函数获取用户输入,然后从中创建一个文件夹,并尝试将chdir()放入该文件夹,然后再创建两个文件。但是,当我试图通过finder(手动)访问文件夹时,我没有权限。不管怎样,这是我的代码,有什么提示吗 int newdata(void){ //Declaring File Pointers FILE*passwordFile; FILE*usernameFile; //Variables for cha

我是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;


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

您应该包括原型的头文件
,然后实际调用函数:

if (chdir(accountType) == -1)
{
    printf("Failed to change directory: %s\n", strerror(errno));
    return;  /* No use continuing */
}
未调用函数,请尝试以下代码:

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字符串:

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

这行代码很奇怪:
intchdir(char*accountType)
如果您不介意我问您,我将如何切换到accountType目录并创建代码中后面的两个文件?对不起,我是新来C的,谢谢你的回答。
printf("%s\n", accountType);