Changing working directory in C?

Dragan Marjanovic picture Dragan Marjanovic · Jan 6, 2013 · Viewed 11.2k times · Source

Im new to C and am having trouble using chdir(). I use a function to get user input then I create a folder from this and attempt to chdir() into that folder and create two more files. Howver when I try to access the folder via finder (manually) I dont have permissions. Anyway here is my code for that, any tips?

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;


}

Answer

Some programmer dude picture Some programmer dude · Jan 6, 2013

You don't actually change the directory, you just declare a function prototype for chdir. You then continue to compare that function pointer against zero (which is the same as NULL) which is why it fails.

You should include the header file <unistd.h> for the prototype, and then actually call the function:

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