I need to write a binary file to some specified directory using a C program. But, while writing I want to make sure that if the directory structure does not exist it should create one for me.
How can I achieve this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have to check whether the leaf directory exists, using
stat(), and iteratively create directories in a top-down manner, usingmkdir(). Or you may even abandon the check and start with a directory creation – it will just fail with bunch ofEEXISTerrors if your directories are already there. This is just an easy way.If you’re concerned about correctness, there is a better way. You should use
openat()on subsequent available components (directories) of the desired path andmkdirat()to create lacking ones. That way you can avoid possible races. In the end, you should open your file usingopenat()too.Check relevant manpages to see how you should use mentioned system calls.
If the above rod was not sufficiently long enough for you, then below you can find my simple Linux-flavored fish.
xopen()function allows you to open the file in a given path, creating directories along the way.