I am taking a file path from a user. I need to then access that file, and create it if it does not exist. I also need to create any intermediate directories if they don't exist as well.
For example, if my directory looks like:
mydir
|
+---subdir
| |
| +-- FileA
|
+---File1
I might receive mydir/subd开发者_如何学JAVAir/FileA and would then access the relevant file. However, I might also receive mydir/NewDir/FileB.
How can I do this using Unix system calls in C? I have tried using open() with the (O_RDWR | O_CREAT) flags, but this didn't work out.
I think this answer covers your question:
Recursive mkdir() system call on Unix
In short, you must create the subdirs yourself.
If you are allowed to use it, OS calls can be wrapped inside system()
call. e.g. for listing files system( "ls" );
To create a directory including the intermediate ones, use mkdir
with -p
mkdir -p mydir/NewDir/
(AFAIK, it doesn't hurt if NewDir already existed.)
To create an empty file, use touch
touch mydir/NewDir/FileB
Followup: I wrote this quick proof-of-concept program and tested in cygwin.
#include <stdlib.h>
#include <string.h>
int main() {
char const * dir = "dir/subdir";
char const * file = "file";
char mkdirCmd[ 80 ] = { 0 };
strcat( mkdirCmd, "mkdir -p " );
strcat( mkdirCmd, dir );
char touchCmd[ 80 ] = { 0 };
strcat( touchCmd, "touch " );
strcat( touchCmd, dir );
strcat( touchCmd, "/" );
strcat( touchCmd, file );
system( mkdirCmd );
system( touchCmd );
return 0;
}
Unit test:
$ ls
mkdir.c mkdir.exe*
$ ./mkdir.exe
$ ls
dir/ mkdir.c mkdir.exe*
$ ls -R dir
dir:
subdir/
dir/subdir:
file
Unfortunately there is no recursive 'makedir' so I'm scared that you might have to do it yourself.
But I think its gonna be easy doing it
function recursiveCreate(filepath) split the filepath by slash if last part create file else create directory end
Now you have your function :) using it will make you happier than using some UNIX defined function :)
精彩评论