MAX_PATH 还是 MAX_PATH + 1 ?

标签: , , , ,

很多人以为 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<NUL>" where "<NUL>" 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];
赞赏

微信赞赏支付宝赞赏

随机文章:

  1. VBS深入CreateObject函数
  2. MySQL整数类型TINYINT SMALLINT MEDIUMINT INT BIGINT
  3. 在Raspberry Pi 2树莓派2上安装Node.js
  4. VBS获取文件的SDDL字符串
  5. 吞噬者批处理编写器

留下回复