windows 在 C++ 中,我如何验证文件或文件夹路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2008707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:41:46  来源:igfitidea点击:

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

c++windows

提问by brad

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

目标路径的用户输入字符串可能包含空格或其他无效字符。

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

示例:“ 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?

在尝试对其进行任何操作之前,如何证明该路径有效?

回答by Michael

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

“证明”路径有效的唯一方法是打开它。

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

SHLWAPI提供了一组路径函数,可用于规范化路径或验证路径是否有效。这对于拒绝明显错误的路径很有用,但您仍然不能相信不通过文件系统的路径是有效的。

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

使用 NTFS,我相信您提供的路径实际上是有效的(尽管资源管理器可能不允许您创建一个只有空格的目录。)

回答by Ricardo Mu?oz

The Boost Filesystemlibrary provides helpers to manipulate files, paths and so... Take a look at the simple ls exampleand the existsfunction.

提高文件系统库提供助手来操作的文件,路径等等......看看在简单的例子LS存在的功能。

回答by Bob Moore

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.

我使用 GetFileAttributes 来检查是否存在。适用于两个文件夹(在返回值中查找 FILE_ATTRIBUTE_DIRECTORY 标志)和文件。我已经这样做了多年,从来没有遇到过问题。

回答by Void

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 Ricardopointed out.

如果您不想打开文件,您也可以使用类似access()POSIX 平台上的函数或_access()Windows 上的朋友。但是,我喜欢Ricardo指出的 Boost.Filesystem 方法。