Create a file and its parents directories in c

时光总嘲笑我的痴心妄想 提交于 2019-12-11 16:42:03

问题


I didn't find any relevant answer for this question.

I want to create a file and its parent directory at the same time:

example:

FILE *fd2 = fopen("test/test", "w+");

where test/ doesn't exist.

Is there a way to do this?


回答1:


In Linux you can do it with the following code

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
... 
/* check if directory exist */
struct stat status = { 0 };
if( stat("test", &status) == -1 ) {
  /* create it */
  mkdir( "test", 0700 );
}
/* open file */
FILE *fd2 = fopen("test/test", "w+");
... 

For the situation when file test exists in first if statement (stat return value is zero), you can also check if this is a file or a directory using macros S_ISREG and S_ISDIR and field st_mode of stat struct.



来源:https://stackoverflow.com/questions/28247719/create-a-file-and-its-parents-directories-in-c

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