MAX_PATH 还是 MAX_PATH + 1 ?
MAX_PATH 还是 MAX_PATH + 1 ? | Demon's Blog
http://demon.tw/programming/max_path-or-max_path-1.html
标签: C, C语言, MAX_PATH, NUL, Windows API
标题: MAX_PATH 还是 MAX_PATH + 1 ?
作者: Demon
链接: http://demon.tw/programming/max_path-or-max_path-1.html
版权: 本博客的所有文章,都遵守“署名-非商业性使用-相同方式共享 2.5 中国大陆”协议条款。
很多人以为 Windows 限制文件最长路径或目录最长路径是 260 个字符,所以经常写以下代码:
//特别加1用来保存 NUL 结束符 TCHAR szPath[MAX_PATH + 1];
其实是错误的,MSDN 上已经说的很清楚了:
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:*some 256-character path string*
" where " " represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
除了下面段落讨论的一些例外,在 Windows API 中路径的最大长度是 260 个字符,例如,D 盘中最长的路径为:
D:\some 256-character path string<NUL>
可以看出这 260 个字符中已经包含了C语言字符串的 NUL 结束符,即文件路径最长只能包含 259 个可见字符。
同时,目录路径还有另一个限制:
When using an API to create a directory, the specified path cannot be so long that you cannot append an 8.3 file name (that is, the directory name cannot exceed MAX_PATH minus 12).
也就是说,目录路径最多只能包含 248 个可见字符。
综上所述,正确的写法应该是:
TCHAR szPath[MAX_PATH];
发表评论