1

I'm trying to write a function that creates a folder inside a folder for example: 'outerfolder/innerfolder' but when I put it inside the mkdir function I get an error, how am I suppose to do that?

int check;
char* dirname = "outerfolder/innerfolder";


check = mkdir(dirname);

// check if directory is created or not 
if (!check)
    printf("Directory created\n");
else {
    printf("Unable to create directory\n");
    exit(1);
}

which doesnt work.

Alexander
  • 1,288
  • 5
  • 19
  • 38
  • 1
    What error are u getting? – R4444 May 05 '19 at 17:55
  • Check the value of `errno` for more information about what happened, or use `perror()`. One note is that `outerfolder` needs to already exist, so if you want to create both, you'll need to call `mkdir()` twice. – Nate Eldredge May 05 '19 at 17:56
  • I tried making a new folder that does not exist , still won't let me – Alexander May 05 '19 at 17:58
  • See: [How can I create directory tree in C++/Linux?](https://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux) — Even though the question is tagged C++, the code shown in my answer is explicitly C code that can be compiled with a C++ compiler (without change of meaning). Also consider the merits and demerits of `system("mkdir -p outerfolder/innerfolder");`. – Jonathan Leffler May 05 '19 at 18:49

1 Answers1

0

try this:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

from Creating a new directory in C

  • doesn't work, unistd won't allow me top open. – Alexander May 05 '19 at 18:02
  • make sure you (your program) have the access rights you need (admin).. also try wit 777 to enable all prophiles to read write and execute rights for the moment.. –  May 05 '19 at 18:08
  • 1
    You have to create `/some` first, if it doesn't exist, and only then `/some/directory`. This code doesn't attempt to do that. – Jonathan Leffler May 05 '19 at 18:50
  • the point is not to reinvent the wheel..creating a recursive version of the standard `mkdir` function is not good idea.. may be he should create the logic to use `mkdir` for creating nested directories.. –  May 05 '19 at 19:04