Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass a string literal like ("~/test/foo") in mkdir function in C programming? [duplicate]

Tags:

c

arguments

mkdir

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

like image 693
programmer Avatar asked Dec 27 '22 10:12

programmer


2 Answers

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

like image 73
Michael Krelin - hacker Avatar answered Jan 05 '23 18:01

Michael Krelin - hacker


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;                                                                     
}   
like image 30
perreal Avatar answered Jan 05 '23 19:01

perreal