tags:

views:

584

answers:

5

A user input string for a destination path can potentially contain spaces or other invalid characters.

Example: " C:\users\username\ \directoryname\ "

Note that this has whitespace on both sides of the path as well as an invalid folder name of just a space in the middle. Checking to see if it is an absolute path is insufficient because that only really handles the leading whitespace. Removing trailing whitespace is also insufficient because you're still left with the invalid space-for-folder-name in the middle.

How do i prove that the path is valid before I attempt to do anything with it?

+6  A: 

The only way to "prove" the path is valid is to open it.

SHLWAPI provides a set of path functions which can be used to canonicalize the path or verify that a path seems to be valid. This can be useful to reject obviously bad paths but you still cannot trust that the path is valid without going through the file system.

With NTFS, I believe the path you give is actually valid (though Explorer may not allow you to create a directory with only a space.)

Michael
Exactly. I don't see what "validity" constraints this violates. It's asking for a direcotry named "directoryname" inside a subdirectory of "username" named " ". If there are application-specific validity constraints, they'll need to be coded in the application. And in any case, simply calling fopen() on the path with the appropriate arguments is enough to tell you whether you can, y'know, open it.
Andy Ross
+2  A: 

The Boost Filesystem library provides helpers to manipulate files, paths and so... Take a look at the simple ls example and the exists function.

Ricardo Muñoz
+1  A: 

I use GetFileAttributes for checking for existence. Works for both folders (look for the FILE_ATTRIBUTE_DIRECTORY flag in the returned value) and for files. I've done this for years, never had a problem.

Bob Moore
Thye one obvious point where this method fails is of course when you're validating paths that don't exist yet, e.g. before attempting to create a directory.
MSalters
If it doesn't exist yet the path isn't valid. Validating a path as *possibly* valid is a different problem from validating a path as valid. Depends what the OP means by "valid" of course.
Bob Moore
A: 

While I actually think you are better off "opening" then theoretically testing, you might want to look into a regex like the one described here.

Liz Albin
A: 

If you don't want to open the file you can also use something like the access() function on POSIX-like platforms or _access() and friends on Windows. However, I like the Boost.Filesystem method Ricardo pointed out.

Void