Rorschach Rorschach - 22 days ago 5
C Question

Making a directory with a c program

I am trying to make a C program which takes a string and makes a directory with the given name. I have made two versions thus far and they are included below but neither work like I want them to.
But this program has 2 problems:
1. It doesn't take input until after you click enter
2. It makes the directory end with a question mark.

//Make Directory program

#include<stdio.h>
#include<string.h>



void main()
{
char dirname[20];
fgets(dirname, 20, stdin);
int check;
check = mkdir(dirname);
printf("This is the chosen directory name: ");
printf(dirname);

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

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

return;

}


I also tried this version.
But it segfaults whenever I try to run it.
I have tried the inputs.
"directory"
and
directory

//Make Directory program

#include<stdio.h>
#include<string.h>
void main( char dirname[20])
{
int check;
checker = mkdir(dirname);

if (!checker)
printf("Directory created\n");

else
{
printf("Unable to make directory\n");
}
return;
}


Any help would be greatly appreciated




Edit:
Here is the new code edited given the suggestions below

When I enter:
$ makedir directory

it makes a directory named:
p?????

Thank you very much for your help so far.

//Make Directory program

#include<stdio.h>
#include<string.h>



void main(int argc, char *argv[])
{
// char dirname[20];
// fgets(dirname, 20, stdin);
int check;
check = mkdir(argv, '.');
//mkdir(argv, '.');

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

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

return;

}

Answer

mkdir takes const char * as an argument not a array of pointers.

int mkdir(const char *pathname, mode_t mode);

as described in the manual page

http://man7.org/linux/man-pages/man2/mkdir.2.html

try:

  int check;
  //the index of your parameter
  check = mkdir(argv[1], 0755);
  //mkdir(argv, '.');