【问题标题】:Creating a file exceeding filepath limit创建超出文件路径限制的文件
【发布时间】:2012-05-21 16:40:05
【问题描述】:

我有一个测试,它会在循环中创建一系列文件夹,直到它超过 MAX_PATH (260)。这将返回 ERROR_PATH_NOT_FOUND(0x3)。我们有一台运行此测试的构建机器,但在构建机器上它返回 ERROR_FILENAME_EXCED_RANGE (0xce)。

我的机器是 Windows 7,但构建机器是 Vista。这可能是他们返回不同值的原因吗?如果没有,有谁知道为什么会发生这种情况?

编辑:我预计会出错,我正在测试文件系统驱动程序。我只是不明白为什么我从不同机器上的同一个测试中得到两个不同的错误代码。 这是代码

homeDir

string childDir = "\\LongChildDirectoryName";
string dir = homeDir.str();
DWORD lastErr = ERROR_SUCCESS;
while(lastErr == ERROR_SUCCESS) 
{
    int len = dir.size();
    if(len > (MAX_PATH - 12))
    {
        CuFail(tc, "Filepath greater than max allowed should be");
    }

    dir += childDir;

    if(!CreateDirectory(dir.c_str(), NULL))
    {
        lastErr = GetLastError();
        if (lastErr == ERROR_ALREADY_EXISTS)
            lastErr = ERROR_SUCCESS;
    }
}
CuAssert(tc, "Check error is ERROR_PATH_NOT_FOUND", lastErr == ERROR_PATH_NOT_FOUND);

【问题讨论】:

  • 您需要发布代码。在我的 Win7 机器上,我收到 ERROR_FILENAME_EXCED_RANGE,所以这不是 Vista 与 Win7 的区别。

标签: windows file winapi


【解决方案1】:

逻辑有问题。如果 homeDir.str() 返回一个不存在的名称,则 CreateDirectory 的返回值将是 ERROR_PATH_NOT_FOUND。您可以通过简单地执行以下操作来演示问题:

string childDir("\\LongChildDirectoryName");
string dir("foo");

CreateDirectory 调用将获得路径 foo\LongChildDirectoryName,如果 foo 不存在,您将获得 ERROR_PATH_NOT_FOUND。解决方法是在 while 循环之前添加它:

CreateDirectory(dir.c_str(), NULL);

您还需要在连接字符串之后而不是之前移动长度检查。使用 Alex 建议的 "\\?\" 语法也是一个好主意。

【讨论】:

    【解决方案2】:

    要使用更长的路径,您需要使用“宽”版本的CreateFile()CreateFileW()

    看到这个MSDN article的主题:

    HANDLE WINAPI CreateFile(
      __in      LPCTSTR lpFileName,
      __in      DWORD dwDesiredAccess,
      __in      DWORD dwShareMode,
      __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
      __in      DWORD dwCreationDisposition,
      __in      DWORD dwFlagsAndAttributes,
      __in_opt  HANDLE hTemplateFile
    );
    
    lpFileName [in]
    
        The name of the file or device to be created or opened.
    
        In the ANSI version of this function, the name is limited to MAX_PATH characters.
    To extend this limit to 32,767 wide characters, call the Unicode version of the
    function and prepend "\\?\" to the path. For more information, see Naming Files,
    Paths, and Namespaces.
    

    【讨论】:

    • 这不是问题。问题是为什么他得到的是 ERROR_PATH_NOT_FOUND 而不是 ERROR_FILENAME_EXCED_RANGE。
    • 如果他的代码使用 CreateFileW(L"\\\\?\\...") 那么其他一些与之结合使用的代码不是和/或截断文件名。我没有看到其他解释。
    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多