Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

windows

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?

like image 651
brad Avatar asked Jan 22 '23 19:01

brad


2 Answers

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

like image 82
Michael Avatar answered Jan 25 '23 09:01

Michael


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

like image 34
Ricardo Muñoz Avatar answered Jan 25 '23 08:01

Ricardo Muñoz