在 C 中更改工作目录?

标签 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;


}

最佳答案

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

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

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

关于在 C 中更改工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14179559/

相关文章:

c - 为什么当我向 atof() 函数传递一个数字后带有无效字符的字符串时,atof() 函数不返回 0?

c - 使用ptrace获取机器指令

c# - Diffie-Hellman 与 BIGNUM (OpenSSL) 与 BigInteger (C#)

c - 链表节点的大小

c++ - 强制结构大小为 8 字节

c - 使用 chdir() 而不是绝对路径进行目录遍历

batch-file - 批处理脚本失败并显示 "The system cannot find the path specified"

python os.path.realpath 无法正常工作

java - 为什么 user.dir 系统属性在 Java 中有效?