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;
}
The pwd command can be used to determine the present working directory. and the cd command can be used to change the current working directory.
Often, you may want to change the current working directory, so that you can access different subdirectories and files. To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.
In the shell, the command cd - is a special case that changes the current working directory to the previous working directory by exchanging the values of the variables PWD and OLDPWD. Note: Repeating this command toggles the current working directory between the current and the previous working directory.
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 */
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With