Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

running system() with a variable inside?

Status
Not open for further replies.

cyburdine

Programmer
Mar 12, 2002
3
US
I am looking for a way to create a directory based on user input. I am using the system() function.

I basically want to run system("mkdir BOB");
where BOB is a variable that users define.

is there a better way of doing this?

int main()
{
string webName;

cout << &quot;Enter the dir name: &quot;;
cin >> dirName;
system(&quot;mkdir dirName&quot;);
}

 
ok, so I learned that when ya need to call mkdir... call mkdir().

man 2 mkdir

ya sure can learn alot from those man pages... ;)

 
Yes cyburdine is right,

You can use the following code.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main()
{
char name[100];
fgets(name, 99, stdin);
name[strlen(name) -1] = 0; // to remove the \n character
if( mkdir(name, 0777) < 0) // here the initial permision of the directory would be 0777 & ~ umaks
{
perror(&quot;Error in creating the directory&quot;);
exit(-1);
}
else
{
cout << &quot;The directory&quot; << name << &quot; Created&quot;;
}
return 0;
}


or put a sprintf like

char name[100];
sprintf(name, &quot;mkdir %s&quot;, dirName);
system(name);

in your code.

Regards,
Maniraja S
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top