4

Possible Duplicate:
How can I create directory tree in C++/Linux?
Why mkdir fails to work with tilde (~)?

i'm trying to create a directory in a C program and i use the mkdir function. My program is as follows:

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

 #define MKDIR(x)  mkdir(x)

 int main() {

      //If i do mkdir("foo"), the dir is created 

      mkdir("~/test/foo"); //Directory foo not created inside test dir
 }

The dir foo isn't created in Test dir.

But how can i achieve that? Thanks, in advance

Community
  • 1
  • 1
programmer
  • 4,571
  • 13
  • 49
  • 59

2 Answers2

9

mkdir() function doesn't expand ~ shortcut, you'll have to pull the value from the HOME environment variable. (see man getenv).

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • Thanks, for replying. I tested with the HOME variable. In the program i have to make, i shall not create a dir in the home directory, but in a destination folder which is not in my home directory.Is there any other way to define the specific path of the mkdir function without using getenv? – programmer Nov 26 '11 at 20:06
  • If it's not in the home dir, then you can specify full path like `"/home/youraccount/test/foo"` as literal. – Michael Krelin - hacker Nov 26 '11 at 20:07
  • Yeah, it's working and i also used system("mkdir /test/foo") in order to create a dir.Is system() function slower that mkdir()? – programmer Nov 26 '11 at 20:59
  • 1
    tons slower. Of course you have the benefit of being able to run `mkdir -p`, but you have to escape the directory name if it contains spaces or something worse than that, you can, of course, use `exec*` to run `mkdir`, but, honestly, I think creating directories one by one (if you actually need `-p`) is easier. In short, if you're doing it in c — do it in c. – Michael Krelin - hacker Nov 26 '11 at 21:30
1

check wordexp: http://pubs.opengroup.org/onlinepubs/7908799/xsh/wordexp.html

#include <wordexp.h>                                                            
#include <stdio.h>                                                              
int main() {                                                                    
  wordexp_t p;                                                                  
  if (wordexp("~/", &p, 0)==0) {                                                
    printf("%s\n", p.we_wordv[0]);                                              
    wordfree(&p);                                                               
  }                                                                             
  return 0;                                                                     
}   
perreal
  • 94,503
  • 21
  • 155
  • 181