'How to create a folder in C

How can I create a new folder for an email manager, I have this code but It doesn't work.

 void create_folder() {
   int check;
   char * dirname;
   clrscr();
   printf("Enter a directory path and name to create a folder (C:/name):");
   gets(dirname);
   check = mkdir(dirname);

   if (!check)
     printf("Folder created\n");

   else {
     printf("Unable to create folder\n");
     exit(1);
   }
   getch();
   system("dir/p");
   getch();
 }


Solution 1:[1]

Use this:

 void create_folder() {
   int check;
   char dirname[128];
   clrscr();
   printf("Enter a directory path and name to create a folder (C:/name):");
   fgets(dirname, sizeof(dirname), stdin);
   check = mkdir(dirname);

   if (!check)
     printf("Folder created\n");

   else {
     printf("Unable to create folder\n");
     exit(1);
   }
   getch();
   system("dir/p");
   getch();
 }

Your dirname string was unallocated, use a char array instead.

Solution 2:[2]

I copied from Mahonri Moriancumer's anwer:

void make_directory(const char* name) {
   #ifdef __linux__
       mkdir(name, 777); 
   #else
       _mkdir(name);
   #endif
}

Solution 3:[3]

You would have to allocate memory for dirname.

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#include<dir.h>

#define SIZE 25      //Maximum Length of name of folder

void main() {
    int check;
    char *dirname;
    dirname=malloc(SIZE*sizeof(char));
    printf("Enter a directory path and name to be created (C:/name):");
    gets(dirname);
    check = mkdir(dirname);
    free(dirname);
    if (!check)
        printf("Directory created\n");

    else
    {
        printf("Unable to create directory\n");
        exit(1);  
    } 
    getch();
    system("dir/p");
    getch();
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josh Abraham
Solution 2 Cloud Cho
Solution 3