How to create a file in a specific directory

让人想犯罪 __ 提交于 2019-12-07 08:42:41

问题


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/

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

 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:


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

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


来源:https://stackoverflow.com/questions/16153477/how-to-create-a-file-in-a-specific-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!