Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
Aleksandair Avatar asked Apr 24 '14 14:04

Aleksandair


People also ask

How do you create a folder within a folder in Linux?

With the help of mkdir command, you can create a new directory wherever you want in your system. Just type "mkdir <dir name> , in place of <dir name> type the name of new directory, you want to create and then press enter. Example: mkdir created.

How do I create a folder in WSL terminal?

Right click using computer mouse, select New > Folder. Rename it to “ajeet”. 2. Alternatively, we can create a new folder by running a command in the WSL terminal.

How do I create a folder and subfolders in Linux?

The mkdir command in Linux/Unix allows users to create or make new directories. mkdir stands for “make directory.” With mkdir , you can also set permissions, create multiple directories (folders) at once, and much more.


2 Answers

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(...)

like image 141
Mahonri Moriancumer Avatar answered Oct 06 '22 22:10

Mahonri Moriancumer


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");
like image 44
0x90 Avatar answered Oct 06 '22 22:10

0x90