1

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();
 }
Eric Schnipke
  • 482
  • 1
  • 6
  • 22
Diego Fernández
  • 19
  • 1
  • 1
  • 2
  • 5
    Doesn't seem to work how? Compiler error? Crashes? Computer catches on fire? – tadman Feb 06 '18 at 17:39
  • 4
    You never allocated any memory for `dirname` to point to, so you've got undefined behavior at `gets(dirname)`. Also, `gets()` is deprecated, stop using it. – Barmar Feb 06 '18 at 17:41
  • You in windows right? Use `CreateDirectory` from `windows.h` and `dirname` is uninitialized. – user2736738 Feb 06 '18 at 17:42
  • 1
    BTW don't use `gets`, it's an outdated and dangerous function. – Jabberwocky Feb 06 '18 at 17:44
  • 1
    [See this](https://stackoverflow.com/questions/23271990/how-to-create-a-folder-in-c-need-to-run-on-both-linux-and-windows) – akshayk07 Feb 06 '18 at 17:49

3 Answers3

0

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.

Josh Abraham
  • 959
  • 1
  • 8
  • 18
0

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();
    }
krpra
  • 466
  • 1
  • 4
  • 19
0

I copied from Mahonri Moriancumer's anwer:

void make_directory(const char* name) {
   #ifdef __linux__
       mkdir(name, 777); 
   #else
       _mkdir(name);
   #endif
}
Cloud Cho
  • 1,594
  • 19
  • 22