Create a file and its parents directories in c

2019-08-20 04:01发布

问题:

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.