I'm using fopen("aaa\bbb\ccc\myfile.txt","w")
to create output file. But folders aaa
, bbb
and ccc
don't exist. What is the best way to solve this problem? Is there are any standard way to ask fopen()
to create all needed folders?
The fopen can't be used to create directories. This is because fopen function doesn't create or open folders, it only works with files. The above code creates a path to the file named 'filename'. The directory of the 'filename' is obtained using the 'dirname' function.
The fopen function creates the file if it does not exist. r+b or rb+ Open a binary file for both reading and writing. The file must exist.
Using os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os. makedirs() method will create them all.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With