Within a C project, I'm trying to make a directory within a specific directory.
// Find the user's home directory.
// Code from https://stackoverflow.com/a/2910392/14602523
struct passwd * pw = getpwuid(getuid());
char * home = pw->pw_dir;
// Test if the ".junk" directory exists in the home directory.
// If not, create it.
if (opendir(strcat(home, "/.junk/")) == NULL) {
printf(" - no junk directory\n");
if (mkdir(strcat(home, "/.junk/"), 0777) < 0) {
fprintf(stderr, "Error: Cannot create junk directory.\n");
perror(" - errno");
exit(1);
}
}
opendir()
works correctly: If a directory named .junk/
exists in ~/
, then I don't get any print messages, and if the directory doesn't exist then I get some output. But the mkdir()
is being really finnicky and causing lots of issues. If ~/.junk/
doesn't exist then I get this output:
- no junk directory
Error: Cannot create junk directory.
- errno: No such file or directory
But if I try to make the directory in the current one, such as mkdir("./.junk/", 0777)
, the directory is created correctly. What's going on? Why does it act differently in ~/
and how can I get it to work?