检查文件名是有效的 Windows 名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3085261/
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 14:41:39  来源:igfitidea点击:

Check file name is valid windows name

c++windowsfilefilesystems

提问by user152508

I wanna check if my string is valid windows file path. I was searching around and it seems that there is no reliable method to do that. Also I checked boost filesystem library , and no obvious function exist to do this check , maybe something like is_valid_windows_name

我想检查我的字符串是否是有效的 Windows 文件路径。我四处寻找,似乎没有可靠的方法可以做到这一点。我还检查了boost文件系统库,没有明显的函数来做这个检查,也许像is_valid_windows_name这样的东西

回答by M. Williams

You could use _splitpath()function and parse the output (based on it, you could easily say if your path is valid or not).

您可以使用_splitpath()函数并解析输出(基于它,您可以轻松判断您的路径是否有效)。

See MSDNfor additional information.

有关其他信息,请参阅MSDN

Note that this function is windows-specific.

请注意,此功能是特定于 Windows 的。

回答by codymanix

I do not believe there is a standard c++ api for that.

我不相信有一个标准的 c++ api。

Note that the Windows API allows more filenames than the Windows Shell (The filenames the user is allowed to use in windws explorer).

请注意,Windows API 允许的文件名多于 Windows Shell(允许用户在 windws 资源管理器中使用的文件名)。

You should have a look at the windows shell api.

你应该看看windows shell api。

Another possibility is to use trial and error, this way you are truly independend of the current filesystem.

另一种可能性是使用反复试验,这样您就真正独立于当前文件系统。

The easiest way is to disallow

最简单的方法是禁止

\ / < > | " : ? *

\ / < > | “:?*

and you should be fine.

你应该没事的。

回答by Vladimir Nikulin

Yes, there is a boost function that does what you want. Take a look at boost::filesystem::windows_name(...). You will need to include boost/filesystem/path.hpp as well as link against the correct (version- and architecture-specific) libboost_system and libboost_filesystem libraries since path is not a header-only lib.

是的,有一个增强功能可以满足您的需求。看看 boost::filesystem::windows_name(...)。您将需要包含 boost/filesystem/path.hpp 以及针对正确(特定于版本和体系结构)的 libboost_system 和 libboost_filesystem 库的链接,因为路径不是仅包含头文件的库。

回答by klaus triendl

It's a pity even the newest C++17 filesystem library doesn't have a function to verify file names.

遗憾的是,即使是最新的 C++17 文件系统库也没有验证文件名的功能。

You can use the Windows-specific Shell Lightweight Utility functionPathFileExistsor the Windows APIGetFileAttributesand check the last error code specifically for ERROR_INVALID_NAME.

您可以使用 Windows 特定的Shell Lightweight Utility 函数PathFileExistsWindows APIGetFileAttributes并检查专门针对ERROR_INVALID_NAME.

I think it's kind of a misuse (because there really should be a dedicated function for it) but serves the purpose.

我认为这是一种误用(因为确实应该有一个专门的功能)但可以达到目的。