0

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?

anothertest
  • 979
  • 1
  • 9
  • 24
  • 1
    Yes, create directory "test", then create file "test/test". I believe directory creation is OS specific, so specify your OS. – chux - Reinstate Monica Jan 31 '15 at 03:15
  • I work on linux. Isn't there a way to create automatically the directory? @chux – anothertest Jan 31 '15 at 03:16
  • 2
    Not much happens in C automatically. – chux - Reinstate Monica Jan 31 '15 at 03:17
  • Check http://stackoverflow.com/questions/27431725/how-to-create-a-directory-in-user-space-in-a-linux-kernel-module – chux - Reinstate Monica Jan 31 '15 at 03:19
  • You can create the directory part of the path using the code in [How can I create a directory tree in C++/Linux](http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux/675193), which actually has a bilingual answer with code that's both C and C++. You need the [`dirname()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/dirname.html) function to get the directory part of the name. It will be two separate operations — create the directories, then create the file. – Jonathan Leffler Jan 31 '15 at 04:25
  • May find [this interesting](http://stackoverflow.com/questions/6700185/create-a-directory) as well. – WhozCraig Jan 31 '15 at 05:01
  • 1
    @chux and that is good thing. – Ryan Jan 31 '15 at 05:12

1 Answers1

0

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.

Nikolay K
  • 3,770
  • 3
  • 25
  • 37