5

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;


}
Dragan Marjanovic
  • 1,287
  • 5
  • 16
  • 27

2 Answers2

5

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 */
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • So if you dont mind me asking how would I change into accountType directory and create the two files that follow in the code? Sorry Im new to C. =/ and thanks for the answer. – Dragan Marjanovic Jan 06 '13 at 14:12
3
int chdir(char *accountType); 

is not calling the function, try following code instead:

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");
}

also, the printf line looks suspicious, I think you want is print accountType string:

printf("%s\n", accountType);
alk
  • 69,737
  • 10
  • 105
  • 255
fluter
  • 13,238
  • 8
  • 62
  • 100