brad
brad

Reputation: 51

In C++ how do i validate a file or folder path?

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?

Upvotes: 5

Views: 16556

Answers (4)

Void - Othman
Void - Othman

Reputation: 3481

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.

Upvotes: 0

Bob Moore
Bob Moore

Reputation: 6894

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.

Upvotes: 1

Ricardo Muñoz
Ricardo Muñoz

Reputation: 339

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

Upvotes: 2

Michael
Michael

Reputation: 55415

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.)

Upvotes: 6

Related Questions