views:

430

answers:

4

I found many examples of CreatingDirectory recursively, but not the one I was looking for.

here is the spec

Given input

  1. \\server\share\aa\bb\cc
  2. c:\aa\bb\cc

USING helper API

 CreateDirectory (char * path)
 returns true, if successful
 else
 FALSE

Condition: There should not be any parsing to distinguish if the path is Local or Server share.

Write a routine in C, or C++

A: 

Just walk through each directory level in the path starting from the root, attempting to create the next level.

If any of the CreateDirectory calls fail then you can exit early, you're successful if you get to the end of the path without a failure.

This is assuming that calling CreateDirectory on a path that already exists has no ill effects.

therefromhere
The only thing to watch is the different errors for 'lack of permission' vs 'directory already exists'. Attempting to create a directory that exists will just fail (unless you're on an antique version of NFS, when all sorts of odd-ball things could happen).
Jonathan Leffler
+1  A: 

Totally hackish and insecure and nothing you'd ever actually want to do in production code, but...

Warning: here be code that was typed in a browser:

int createDirectory(const char * path) {
  char * buffer = malloc((strlen(path) + 10) * sizeof(char));
  sprintf(buffer, "mkdir -p %s", path);
  int result = system(buffer);
  free(buffer);
  return result;
}
Dave DeLong
There are worse ways to do it. Once upon a few decades ago, it would have been necessary: in Version 7 Unix, `mkdir` was a SUID root program and there was no `mkdir()` system call (but neither was there a `-p` option to `mkdir`).
Jonathan Leffler
A: 

The requirement of not parsing the pathname for server names is interesting, as it seems to concede that parsing for / is required.

Perhaps the idea is to avoid building in hackish expressions for potentially complex syntax for hosts and mount points, which can have on some systems elaborate credentials encoded.

If it's homework, I may be giving away the algorithm you are supposed to think up, but it occurs to me that one way to meet those requirements is to start trying by attempting to mkdir the full pathname. If it fails, trim off the last directory and try again, if that fails, trim off another and try again... Eventually you should reach a root directory without needing to understand the server syntax, and then you will need to start adding pathname components back and making the subdirs one by one.

DigitalRoss
+1  A: 

How about using MakeSureDirectoryPathExists() ?

Stefan