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. OpenWrt实现WOL(Wake-on-LAN)网络唤醒
  2. WordPress判断用户是否登录
  3. InputBox与两数相加——一个简单的VBS脚本问题
  4. wprintf输出中文
  5. VBScript编译器(VBS也疯狂)

留下回复