I'm using fopen("aaa\bbb\ccc\myfile.txt","w")
to create output file. But folders aaa
, bbb
and ccc
does't exists. What is the best way to solve this problem? Is there are any standard way to ask fopen to create all needed folders?
As others have noted, there is no cross-platform support for directories in the C standard library.
As far as my understanding goes, fopen()
and friends don't even know or care that the /
-es or \
-es in the path you give them are used as directory separators in the two major operating system families in use today.
For a cross-platform solution for single directory creation, see @dbush 's answer.
You can then wrap this with a function of your own that will take the complete file/directory path including all parent folders and create all the required parent folders (if needed), one-by-one.
For this, you will need to devise a way of extracting out each successive parent directory from your file path, starting from the top-most/left-most directory. Take care with splitting strings in C, as functions like strtok()
can be unsafe —you might be better off with a different approach for converting the path into a list of directories to create.
You may also need to handle cases where directories already exist, or where a file exists at a path where you wanted to place one of your directories.