How can I create a file as well as missing dirs along the path in linux system programatically?

1.6k Views Asked by At

I want to create a file on linux system in my program, say /a/b/c/test, currently I only have dir /a exist and I want to do it in my program, is there any function that can create file as well as missing dirs (that is, create b/c/test) in one deal? open, fopen, mkdir all seem can't work if there are missing dirs along the path. Thank you.

4

There are 4 best solutions below

3
On BEST ANSWER

From strace mkdir -p a/b/c:

mkdir("a", 0751)                        = 0
open("a", O_RDONLY|O_NOCTTY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_NOFOLLOW) = 3
fchdir(3)                               = 0
close(3)                                = 0
mkdir("b", 0751)                        = 0
open("b", O_RDONLY|O_NOCTTY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_NOFOLLOW) = 3
fchdir(3)                               = 0
close(3)                                = 0
mkdir("c", 0751)                        = 0

In other words, you have to call mkdir() yourself, in a loop per directory, then create the file. This is how the mkdir exe does it (in C). Why not run the mkdir -p /a/b/c command with execve? With C stuff set up for the call properly, of course.

1
On

I think you need two commands:

$ mkdir -p /a/b/c/ && touch /a/b/c/test
0
On

Sorry, you will have to be satisfied with a two-step process:

mkdir -p /a/b/c
touch /a/b/c/test
0
On

If you are using Glib (the lowest level library of Gtk, which can be used independently) you could just call g_mkdir_with_parents to make all the directories (like the mkdir -p command does)