【问题标题】:How to create a file in a specific directory如何在特定目录中创建文件
【发布时间】:2013-04-15 17:32:21
【问题描述】:

我已经找到了一种方法来做我想做的事,但它看起来很脏。我只想做一件简单的事

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

【问题讨论】:

    标签: c file mkdir


    【解决方案1】:

    试试这个,它有效。我改变了什么:我用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);
        }   
    }
    

    【讨论】:

    • mmh 我不确定.. 我还没有告诉你这是程序的一部分,我们要在目录中移动的文件是我从套接字接收的文件..我不知道我是否可以毫无风险地使用 fopen
    • 文件从哪里得到并不重要,只要它在磁盘上。
    • 很高兴我能帮上忙。如果您能将答案标记为正确,我将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2018-07-17
    • 2021-08-31
    • 2012-01-13
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多