Originally Posted by
Jimmy
You should probably use MAXPATHLEN like below
It's not actually a reliable limit. For example, in Linux systems the limit may depend on filesystem. The actual limit for a file in the current directory is pathconf(".", _PC_NAME_MAX);
On the other hand, if you're using Linux or BSDs, it's easier just to use asprintf():
Code:
char *dirname = NULL;
dirname = asprintf("hinesro.rooms.%ld", (long)getpid());
if (dirname == NULL) {
fprintf(stderr, "Out of memory.\n");
exit(EXIT_FAILURE);
}
if (mkdir(dirname, 0755) == -1) {
fprintf(stderr, "Cannot create '%s'.\n", dirname);
exit(EXIT_FAILURE);
}
fprintf(stdout, "Directory '%s' created successfully.\n", dirname);
fflush(stdout);
free(dirname);
dirname = NULL;
The operating system will complain, if the file/directory name is too long or otherwise unsuitable.
A directory created and named thus has the property that its creation is atomic even on NFS filesystems, unlike files. That is, if you create such a directory this way, no other machine using the same filesystem has succeeded creating such a directory (unless they or somebody else removed or renamed the directory in between).
I find the interface to the printf() family of functions a bit annoying, so I often use my own variants using stdargs:
Code:
size_t my_print(char **const strptr, size_t *const sizeptr, const char *const format, ...);
size_t my_cat(char **const strptr, size_t *const sizeptr, const char *const format, ...);
which basically take the address of the string pointer, the address of the allocated length for the string, and the printf format string and whatever parameters it uses, and returns the length of the resulting (dynamically allocated/reallocated) string, or zero with errno set to nonzero if an actual error occurred; typically ENOMEM. So, basically a cross between snprintf() and getline(). Internally uses strlen(), snprintf() and realloc().