Aleksandair
Aleksandair

Reputation: 177

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.

Upvotes: 8

Views: 12385

Answers (3)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6013

Here is a common 'create directory' method:

#include <sys/stat.h>
#ifdef _WIN32
#include <direct.h>
#endif
void make_directory(const char* name) 
   {
   #ifdef __linux__
       mkdir(name, 0777); 
   #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(...)

Upvotes: 8

0x90
0x90

Reputation: 41002

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");

Upvotes: 2

user3566272
user3566272

Reputation: 55

As I know, you can use the cd (change directory) command to create folder. You can use the rmdir command to delete empty directories. If you want to delete the directory with its contents, use rm -rf name-of-the-directory. The -rf specifies to force the deletion and to do it recursively.

You can use these using the command line, but if you want to do this programmatically, I'd say that PHP is suitable to do such.

Upvotes: -9

Related Questions