I already find a way to do what I want, but it seem dirty. I just want to do a simple thing
sprintf(serv_name, "Fattura-%i.txt", getpid());
fd = open(serv_name, PERMISSION | O_CREAT);
if (fd<0) {
perror("CLIENT:\n");
exit(1);
}
I want that the new file, instead of be created in the directory of my program, it's created directly in a subdirectory. example my files are in ./program/ i want that the files will be created in ./program/newdir/
I tried to put directly in the string "serv_name" the path that I want for the file, it was like
sprintf("./newdir/fattura-%i.txt",getpid());
Also tried the \\ and not the /. How can this be done? The only way that I found was, at the end of the program, put a:
mkdir("newdir",IPC_CREAT);
system("chmod 777 newdir");
system("cp Fattura-*.txt ./fatture/");
system("rm Fattura-*.txt");
Try this, it works. What I changed: I used fopen
instead of open
and I used snprintf
instead of sprints
, because it's safer:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
char serv_name[1000];
mkdir("newdir", S_IRWXU | S_IRWXG | S_IRWXO);
snprintf(serv_name, sizeof(serv_name), "newdir/Fattura-%i.txt", getpid());
FILE* f = fopen(serv_name, "w");
if (f < 0) {
perror("CLIENT:\n");
exit(1);
}
}
来源:https://stackoverflow.com/questions/16153477/how-to-create-a-file-in-a-specific-directory