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

StackOverflow https://stackoverflow.com/questions/10826978

  •  11-06-2021
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I think you need two commands:

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

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

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

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top