I want to create a directory that has the name ends with the process ID (to make it unique) and then store the new files that I just wrote inside that directory.
What I want:
1) Create a new directory named : mydirectory.1923 (example of the process id number)
2) Store a file that I just created using
FILE * fPointer = fopen("new.txt",w+)
into mydirectory.1923
What I have so far is this:
int bufSize = 20;
int pid = getpid();
char *fileName = malloc(bufSize);
char *prefix = "that.rooms.";
snprintf(fileName, bufSize,"%s%d", prefix, pid);
printf("%s\n",fileName);
struct stat st = {0};
if (stat(fileName, &st) == -1) {
mkdir(fileName, 0755);
}
DIR *dir = opendir (fileName);
if (dir != NULL) {
FILE *fLib = fopen("library.txt" , "w+");
fclose(fLib);
}
closedir(fileName);
return 0;
My Question:
This code doesn't work, apparently it says error on the DIR part.
Is this the right thing to do if I want to create directory, create file and store that file directly to the new directory?
Is there any suggestion or advice to do it better than this? Thank you.
Some comments:
PATH_MAX
and FILE_MAX
in limits.h
closedir
function receives a DIR *
argument, which I suppose would be dir
in your code. chdir
to it before the fopen
call. I don't recommend the latter as it affects the process wide working directory. Below is a quick and dirty patched version of your code that creates the directory and the new file inside it taking into account the above:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <limits.h>
int main(int argc, char **argv){
int pid = getpid();
char dirName[NAME_MAX+1];
char *prefix = "that.rooms.";
snprintf(dirName, NAME_MAX + 1,"%s%d", prefix, pid);
printf("%s\n",dirName);
struct stat st = {0};
if (stat(dirName, &st) == -1) {
if(mkdir(dirName, 0755) != -1){
char libPath[PATH_MAX+1];
snprintf(libPath, PATH_MAX + 1, "%s/library.txt", dirName);
FILE *fLib = fopen(libPath , "w+");
fclose(fLib);
}else{
perror("mkdir: ");
}
}
return 0;
}
Changed the variable names a bit so it's clearer:
dirName
is used to hold the directory name. It uses NAME_MAX
as this is the system limit for the length of a file name libPath
is used to hold the path to the library.txt
file you are creating. If your pid was 3123, libPath
would read that.rooms.3123/library.txt
after the snprintf
call. It uses PATH_MAX
as this is the system limit for a the length of a file's path.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.