且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建一个特定目录中的文件

更新时间:2022-11-28 19:16:55

试试这个,它的工作原理。我改变了:我用的fopen 而不是打开我用的snprintf 而不是冲刺,因为它是更安全的:

 的#include<&stdio.h中GT;
#包括LT&; SYS / stat.h>
#包括LT&; SYS / types.h中>
#包括LT&;&unistd.h中GT;
#包括LT&;&stdlib.h中GT;诠释主(){
    炭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);
    如果(F℃,){
        PERROR(客户:\\ n);
        出口(1);
    }
}

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

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