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

标签 c file mkdir

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

    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/

相关文章:

使用指针输入结构值时 scanf 函数中的混淆

java - 为什么我会陷入无限循环

file - sed 在多行匹配后追加

gradle - 在Gradle中测试目录是否存在?

java - 如何在 Java 中以线程安全的方式使用 mkdirs?

c -\c 和\\c 有什么区别?

c - 访问数组内容的可疑语法

c++ - 在 C++ 中转换为 double 时处理异常

java - 文件不想创建新目录(mkdir)?

c++ - C++ 中的定宽整数