如何创建一个特定目录中的文件 [英] How to create a file in a specific directory

查看:108
本文介绍了如何创建一个特定目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到一种方法,做我想做的,但它似乎很脏。我只想做一个简单的事情。

 的sprintf(serv_name,Fattura-%i.txt,GETPID());
    FD =开(serv_name,PERMISSION | O_CREAT);
    如果(FD℃,){
        PERROR(客户:\\ n);
        出口(1);
    }

我想,新的文件,而不是在我的程序的目录中创建,它是直接创建一个子目录。例如我的文件在./program/我想,这些文件将在./program/newdir创建/

我试图直接放在字符串serv_name我想要的文件的路径,它像

 的sprintf(./ NEWDIR / fattura-%i.txt,GETPID());

也试过\\\\,而不是/。如何才能做到这一点?
我发现的唯一办法是,在节目的最后,把一个:

 的mkdir(NEWDIR,IPC_CREAT);
系统(搭配chmod 777 NEWDIR);
系统(CP Fattura - * TXT ./fatture/。);
系统(RM Fattura - * .TXT);


解决方案

试试这个,它的工作原理。我改变了:我用的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);
    }   
}

这篇关于如何创建一个特定目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆