How to create a folder in C (need to run on both Linux and Windows)
Solution 1
Here is a common 'create directory' method:
void make_directory(const char* name)
{
#ifdef __linux__
mkdir(name, 777);
#else
_mkdir(name);
#endif
}
As for removing directories, you are on the right track, ie:
for the moment I delete each files one by one and then the folder with remove(...)
Solution 2
It is not what you should do in production code, but I had to mention that one liner solution no #ifdef
etc. I am Assuming you run it from the same path you want to create the directory in:
system("mkdir my_dir");
Aleksandair
Updated on June 30, 2022Comments
-
Aleksandair almost 2 years
I don't have much experience and I'm on a C project where I need to create & delete folders and the program must run on both Linux and Windows.
I saw few solutions but all were either for Windows or Linux but none for both and most uses system(...).
Also, if there is an easy way to delete a folder with it's contents, I'm interrested (for the moment I delete each files one by one and then the folder with remove(...)) Thanks in advance.
-
Aleksandair about 10 yearsSeems to work despite a "warning implicit declaration of mkdir". and it seems like I don't have right on the new folder. I'll look into it more deeply, thanks.
-
Chris Forrence about 10 yearsYou cannot use
cd
to create a directory, it's a navigation-only command! You'd usemkdir
instead. -
Chris Forrence about 10 yearsAlso, please read this resource on formatting; I've noticed that each of your answers has bad formatting, and it detracts heavily from how an answer is perceived.
-
alk about 10 yearsA "default" umask of
777
is not nice. -
circl about 2 years@Aleksandair You need to include <dirent.h>.