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

3

7

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.

Bairam answered 24/4, 2014 at 14:33 Comment(2)
use pragma #ifdef to switch between fucntions for linux and windows, and also includes according to platformPetras
This question is two questions.Evapotranspiration
S
7

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

Spann answered 24/4, 2014 at 14:42 Comment(3)
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.Bairam
A "default" umask of 777 is not nice.Evapotranspiration
@Bairam You need to include <dirent.h>.Odoric
W
1

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");
Watermark answered 24/4, 2014 at 14:39 Comment(0)
P
-9

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.

Phenylketonuria answered 24/4, 2014 at 14:40 Comment(2)
You cannot use cd to create a directory, it's a navigation-only command! You'd use mkdir instead.Cleave
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.Cleave

© 2022 - 2024 — McMap. All rights reserved.