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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find or create directories in UNIX C

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I have an array of directories, for eg:
array1: dir1
array2: dir2
array3: dir3
array4: dir4
PATH: /dir1/dir2/dir3/dir4

I want to locate and create if necessary the directory structure as shown in the path.

Whats the best way to do this in UNIX C?

thanks
 
The short program below leaves a lot to be desired, but it should give you the basic idea:


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

#define DIRSIZE 200

int main(void)
{
char *s[]={&quot;/dir1&quot;,&quot;/dir2&quot;,&quot;/dir3&quot;,&quot;/dir4&quot;};
char new_dir[DIRSIZE+1];
int i;

for (i=0;s;++i) {
/* insert buffer overflow checking here */
strcat(new_dir,s);
if (mkdir(new_dir,S_IRWXU)==-1) {
perror(&quot;Failed to create directory&quot;);
} else {
printf(&quot;Created %s\n&quot;,new_dir);
}
}
return 0;
}

HTH, [sig]<p>Russ<br><a href=mailto:bobbitts@hotmail.com>bobbitts@hotmail.com</a><br><a href= is in</a><br>[/sig]
 
thats great - thanks,

but how would you first check if the directory exists or not before creating.

otherwise, will that create it only if it doesnt exist?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top