View previous topic :: View next topic |
Author |
Message |
richjoyce n00b
Joined: 22 Oct 2002 Posts: 20 Location: Canada
|
Posted: Sun Oct 12, 2003 9:27 pm Post subject: Simple (well not to me) C++ question about mkdir.. |
|
|
I have this C++ file I want to compile, and it has a line like this:
mkdir(nom);
(nom is a variable), but when i compile it errors with:
foo.cpp:280: `mkdir' undeclared (first use this function)
foo.cpp:280: (Each undeclared identifier is reported only once for
each function it appears in.)
Any ideas on how to fix this? |
|
Back to top |
|
|
MADcow l33t
Joined: 23 Jan 2003 Posts: 742 Location: RIT (Henrietta, New York, United States)
|
Posted: Sun Oct 12, 2003 9:37 pm Post subject: |
|
|
how about including stdlib and using system(command) |
|
Back to top |
|
|
MADcow l33t
Joined: 23 Jan 2003 Posts: 742 Location: RIT (Henrietta, New York, United States)
|
Posted: Sun Oct 12, 2003 9:38 pm Post subject: |
|
|
oh yea, and mkdir and such usually resides in unistd.h (standard unix commands, like sleep and stuff)... you might try including that. |
|
Back to top |
|
|
richjoyce n00b
Joined: 22 Oct 2002 Posts: 20 Location: Canada
|
Posted: Mon Oct 13, 2003 12:55 am Post subject: |
|
|
Ok I changed it to system("mkdir nom"); and it compiles fine, but when i run it it doesn't recognize nom as a variable, it just makes the dir 'nom'...how do i pass variables to system()? |
|
Back to top |
|
|
MADcow l33t
Joined: 23 Jan 2003 Posts: 742 Location: RIT (Henrietta, New York, United States)
|
|
Back to top |
|
|
Target Apprentice
Joined: 25 Apr 2002 Posts: 200
|
Posted: Mon Oct 13, 2003 5:29 am Post subject: |
|
|
Gah! Don't look there. They don't bounds-check.
sprintf() is evil. Use snprintf() instead.
You have to dynamically create a c-type string that contains the full command, and pass that to system(). You can do this by printing into the string to get your variable contents written out properly.
Here:
Code: | #include <limits.h> /* for NAME_MAX */
char cmd[NAME_MAX + 7]; /* "mkdir " + null == 7 */
snprintf(cmd, NAME_MAX + 6, "mkdir %s", nom);
system(cmd);
|
Now, if you're absolutely, completely, positively sure that your variables can never match or exceed the allocated size of the destination string...
...Use snprintf() anyway because you may have missed something.
Or if you're already using STL strings anyway (#include <string>):
Code: | string cmd = "mkdir " + non;
system(cmd.c_str()); |
Alternatively, you could just use the mkdir function by including the correct header:
Code: | #include <sys/stat.h> /* for mkdir() */
if (mkdir(nom, 0755)) { perror(nom); exit(1); } |
|
|
Back to top |
|
|
MADcow l33t
Joined: 23 Jan 2003 Posts: 742 Location: RIT (Henrietta, New York, United States)
|
Posted: Mon Oct 13, 2003 1:54 pm Post subject: |
|
|
Target is right. |
|
Back to top |
|
|
|