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

4

我已经找到了一种实现我想要的功能的方法,但它似乎很不规范。我只是想做一件简单的事情。

    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");
1个回答

2

试试这样做,它很有效。我所做的更改是:我使用了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);
    }   
}

嗯,我不确定…我还没告诉你这是程序的一部分,我们要移动的文件是从套接字接收到的文件,我不知道是否可以使用fopen而不会有风险。 - MarkWarriors
只要文件在磁盘上,其来源并不重要。 - piokuc
很高兴能够帮助您。如果您能将答案标记为正确,我将不胜感激。 - piokuc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接