今天review同事的代码,
发现他对路径长度进行了硬编码,这会产生了潜在的威胁。
以前习惯了用MAX_PATH来定义长度,MAX_PATH是windows自己定义的一个宏,值是260。
为什么是260,后面会谈到。
常见的我们获取当前进程的全路径(绝对路径的方法),一般是调用GetModuleFileName。
TCHAR tszPath[MAX_PATH] = {0};
GetModuleFileName(NULL, tszPath, _countof(tszPath));
//可以获取目录,而不是文件的全路径
PathRemoveFileSpec(tszPath);
//不规范的写法
//在网上也会看到这种写法
//如果tszPath找不到"\\",就会出现崩溃了
_tcsrchr(tszPath, _T('\\'))[1] = '\0';
写法有风险,使用需谨慎。
上面PathRemoveFileSpec函数是shell api,需要包含#include <Shlwapi.h>,并且#pragma comment(lib, "shlwapi.lib"),当然也可以在工程设置中配置link library。
如果是其他进程的模块,可以调用GetModuleFileNameEx。
值得一提的是,使用GetCurrentDirectory有可能得不到预期的结果。因为这个函数是获取当前进程的当前活跃路径。
MSDN在Changing the Current Directory里面提到了
The directory at the end of the active path is called the current directory; it is the directory in which the active application started, unless explicitly changed.
对windows的路径到底有多长产生了兴趣,顺便查看MSDN。
ms-help://MS.MSDNQTR.v90.en/fileio/fs/naming_a_file.htm
其中这样描述到:?
Maximum Path Length
In the Windows API, the maximum length for a path is MAX_PATH, which is defined as 260 characters. A path is structured in the following order: drive letter, colon, backslash, components separated by backslashes, and a null-terminating character, for example, the maximum path on the D drive is D:\<256 chars>NUL.
Note Functions in the Windows API convert "/" to "\" as part of converting the name to an NT style name.
The Unicode versions of several functions permit a maximum path length of approximately 32,000 characters composed of components up to 255 characters in length. To specify that kind of path, use the "\\?\" prefix.
Note The maximum path of 32,000 characters is approximate, because the "\\?\" prefix can be expanded to a longer string, and the expansion applies to the total length.
For example, "\\?\D:\<path>". To specify such a UNC path, use the "\\?\UNC\" prefix. For example, "\\?\UNC\<server>\<share>". These prefixes are not used as part of the path itself. They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory. Also, you cannot use the "\\?\" prefix with a relative path. Relative paths are limited to MAX_PATH characters.
When using the API to create a directory, the specified path cannot be so long that you cannot not append an 8.3 file name.
The shell and the file system may have different requirements. It is possible to create a path with the API that the shell UI cannot handle.
可以看到,上述例子中,D盘最长的路径是D:\<256 chars>NUL。
这里NUL就是结束符,我们常用到的'\0'。
MSDN这段解释中,也提到,使用"\\?\"前缀加上至多255长度的字符串来表示长达约32000个字符的最长路径。
这种真还没有用到过,有用到的童鞋贴个例子,谢谢了。