gpt4 book ai didi

c++ - CreateDirectory 报告失败但错误代码为 ERROR_SUCCESS

转载 作者:可可西里 更新时间:2023-11-01 10:38:53 27 4
gpt4 key购买 nike

我有一个用于创建目录的函数。它使用 CreateDirectoryA()

CreateDirectory 报告失败,但是当我使用 GetLastError() 检查错误代码时,它报告 ERROR_SUCCESS

代码:

BOOL isDirCreated = CreateDirectoryA(dirName.c_str(), NULL);
DWORD dw = GetLastError();
if (isDirCreated) {
if (!SetFileAttributesA(dirName.c_str(), attributes)) {
printf("SetFileAttributes() %s failed with (%d)", dirName.c_str(), GetLastError()));
return;
}
} else {
printf("CreateDirectory() %s Failed with (%d)", dirName.c_str(), dw));
if(ERROR_ALREADY_EXISTS != dw) {
return;
}
}

这将返回:(对该函数的多次调用)

CreateDirectory() testDir Failed with (0)
CreateDirectory() testDir\dir Failed with (183)

即使 CreateDirectoryA 返回 false,目录也会被创建。失败总是发生在第一次调用该函数时。所有后续调用均按预期工作。

知道为什么 CreateDirectory 在成功创建目录时会返回 false。

这是一个类似的帖子,但解决方案对我不起作用:

ReadFile() says it failed, but the error code is ERROR_SUCCESS

更新事实证明,此错误是由于代码中包含的另一个 header 具有函数“GetLastError”而引起的,而另一个函数位于单独的命名空间中,因此解决方案是按如下方式调用 GetLastError。

/*
* the :: will tell it to use the GetLastError that is available on the global
* scope. Most of Microsoft's calls don't have any namespace.
*/
DWORD dw = ::GetLastError();

最佳答案

事实证明,此错误是由于代码中包含的另一个 header 具有函数“GetLastError”而引起的,而另一个函数位于单独的命名空间中,因此解决方案是按如下方式调用 GetLastError。

/*
* the :: will tell it to use the GetLastError that is available on the global
* scope. Most of Microsoft's calls don't have any namespace.
*/
DWORD dw = ::GetLastError();

关于c++ - CreateDirectory 报告失败但错误代码为 ERROR_SUCCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10045495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com