如何在特定的目录中创建文件?

时间:2022-04-14 19:54:54

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/

我希望新的文件不是在程序的目录中创建的,而是直接在子目录中创建的。示例我的文件在。/程序/我希望文件将在。/程序/newdir/。

I tried to put directly in the string "serv_name" the path that I want for the file, it was like

我尝试直接将文件想要的路径放入字符串“serv_name”中,就像这样

 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");

1 个解决方案

#1


2  

Try this, it works. What I changed: I used fopen instead of open and I used snprintf instead of sprints, because it's safer:

试试这个,它的工作原理。改变:我用fopen代替open,用snprintf代替sprint,因为这样更安全:

#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);
    }   
}

#1


2  

Try this, it works. What I changed: I used fopen instead of open and I used snprintf instead of sprints, because it's safer:

试试这个,它的工作原理。改变:我用fopen代替open,用snprintf代替sprint,因为这样更安全:

#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);
    }   
}

相关文章