How to create a folder in C (need to run on both Linux and Windows)

10,783

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");
Share:
10,783
Aleksandair
Author by

Aleksandair

Updated on June 30, 2022

Comments

  • Aleksandair
    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
    Aleksandair about 10 years
    Seems 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
    Chris Forrence about 10 years
    You cannot use cd to create a directory, it's a navigation-only command! You'd use mkdir instead.
  • Chris Forrence
    Chris Forrence about 10 years
    Also, 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
    alk about 10 years
    A "default" umask of 777 is not nice.
  • circl
    circl about 2 years
    @Aleksandair You need to include <dirent.h>.