Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To create all needed folders with fopen

Tags:

c

fopen

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?

like image 912
vico Avatar asked Jan 20 '14 14:01

vico


People also ask

Does fopen create folder?

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.

Can you create a file with fopen?

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.

How do I automatically create a folder in Python?

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.


1 Answers

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.

like image 99
saxbophone Avatar answered Oct 14 '22 06:10

saxbophone