我已经找到了一种方法来做我想做的事,但它看起来很脏。我只想做一件简单的事
sprintf(serv_name, "Fattura-%i.txt", getpid());
fd = open(serv_name, PERMISSION | O_CREAT);
if (fd<0) {
perror("CLIENT:\n");
exit(1);
}
我希望新文件不是在我的程序目录中创建,而是直接在子目录中创建。例如我的文件在 ./program/我希望文件将在 ./program/newdir/中创建
我试图直接在字符串“serv_name”中放入我想要的文件路径,就像
sprintf("./newdir/fattura-%i.txt",getpid());
还尝试了\\而不是/。如何才能做到这一点? 我发现的唯一方法是,在程序结束时,放一个:
mkdir("newdir",IPC_CREAT);
system("chmod 777 newdir");
system("cp Fattura-*.txt ./fatture/");
system("rm Fattura-*.txt");
最佳答案
试试这个,它有效。我改变了什么:我使用 fopen
而不是 open
并且我使用 snprintf
而不是 sprints
,因为它更安全:
#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);
}
}
关于c - 如何在特定目录中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16153477/