【问题标题】:Moving a file using SetFileInformationByHandle使用 SetFileInformationByHandle 移动文件
【发布时间】:2016-04-06 11:46:51
【问题描述】:

我正在尝试使用SetFileInformationByHandle 移动文件。 Niall Douglas 在他的 CppCon2015 演讲“Racing The File System”中提出了这种技术,作为一种以原子方式移动/重命名文件的方法。但是,我正在努力提供正确的论点;它总是失败,GetLastError 返回ERROR_INVALID_PARAMETER。

我已经尝试了以下设置,使用 Unicode 字符集:

  • VS2015U1,在Windows 10下运行exe
  • VS2015U2,在Windows Server 2012下运行exe
  • VS2013,在Windows 7下运行exe

但是行为是一样的。我确保可以访问测试文件夹和测试文件。

#include <sdkddkver.h>
#include <windows.h>

#include <cstring>
#include <iostream>
#include <memory>

int main()
{
    auto const& filepath = L"C:\\remove_tests\\file.txt";
    auto const& destpath = L"C:\\remove_tests\\other.txt";
    // unclear if that's the "root directory"
    auto const& rootdir = L"C:\\remove_tests";

    // handles will be leaked but that should be irrelevant here
    auto const f_handle = CreateFile(filepath,
        GENERIC_READ | GENERIC_WRITE | DELETE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (f_handle == INVALID_HANDLE_VALUE)
    {
        auto const err = GetLastError();
        std::cerr << "failed to create test file: " << err;
        return err;
    }

    auto const parent_dir_handle = CreateFile(rootdir,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
        NULL);

    if (parent_dir_handle == INVALID_HANDLE_VALUE)
    {
        auto const err = GetLastError();
        std::cerr << "failed to get handle to parent directory: " << err;
        return err;
    }

    auto const destpath_bytes_with_null = sizeof(destpath);
    // unclear if we need to subtract the one wchar_t of FileNameLength:
    auto const struct_size = sizeof(FILE_RENAME_INFO) + destpath_bytes_with_null;
    auto const buf = std::make_unique<char[]>(struct_size);

    auto const fri = reinterpret_cast<FILE_RENAME_INFO*>(buf.get());
    fri->ReplaceIfExists =  TRUE; // as described by Niall Douglas
    fri->RootDirectory = parent_dir_handle;
    // with or without null terminator?
    fri->FileNameLength = destpath_bytes_with_null;
    std::memcpy(fri->FileName, destpath, destpath_bytes_with_null);

    BOOL res = SetFileInformationByHandle(f_handle, FileRenameInfo,
                                          fri, struct_size);
    if (!res)
    {
        auto const err = GetLastError();
        std::cerr << "failed to rename file: " << err;
        return err;
    }
    else
        std::cout << "success";
}

特别是,我的问题是:

  • FILE_RENAME_INFO要求的“根目录”是什么?
  • 句柄需要哪些权限?
  • SetFileInformationByHandle产生的ERROR_INVALID_PARAMETER的根本问题是什么?

【问题讨论】:

  • 与this one相同的问题。
  • @HansPassant 好吧,我使用SetFileInformationByHandle 删除 文件没有问题。但是,我无法使用它来 move 文件。另外,我没有使用OpenFileById。您能否更具体地说明我遇到的问题与您链接的问题/答案之间的相似之处?
  • 它的行为方式完全相同,删除 DELETE 即可看到。我猜这是一个 Win10 特定的问题,有人应该和 MSFT 谈谈。我会自愿为你服务。
  • @HansPassant 我现在也在 Windows 7 和 Windows Server 2012 下尝试过,行为与 Windows 10 相同。不幸的是,我仍然看不到与链接帖子的相似之处按磁盘 ID 删除文件。当我删除 DELETE 标志时,我收到拒绝访问错误,而链接问题中的问题是(据我了解)OpenFileByDiskId 似乎忽略了 DELETE 标志,因此生成的句柄不适合与SetFileInformationByHandle 一起使用来删除文件。
  • @Gerardo 我首先要在几个操作系统上测试它。那我就点赞。有没有必要赶紧接受你的回答?我的计划是等待接受答案并提供赏金,直到赏金期结束。

标签: c++ windows winapi file-rename file-move


【解决方案1】:

SetFileInformationByHandle 与 FileRenameInfo 和 FILE_RENAME_INFO 的文档包含一些错误。 FILE_RENAME_INFO.FileNameLength 必须设置为复制到 FILE_RENAME_INFO.FileName 的字符数(不包括终止零),并且 FILE_RENAME_INFO.RootDirectory 必须为空,即使将文件从一个目录移动到另一个目录也是如此。

#include <sdkddkver.h>
#include <windows.h>

#include <cstring>
#include <iostream>
#include <memory>

int _tmain( int argc, _TCHAR* argv [] )
{
    wchar_t* filename = L"C:\\remove_tests\\file.txt";
    wchar_t* destFilename = L"C:\\remove_tests2\\other.txt";

    // handles will be leaked but that should be irrelevant here
    auto fileHandle = CreateFile( filename,
                                  GENERIC_READ | GENERIC_WRITE | DELETE,
                                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                      NULL,
                                      OPEN_EXISTING,
                                      FILE_ATTRIBUTE_NORMAL,
                                      NULL );

    if ( fileHandle == INVALID_HANDLE_VALUE )
    {
        auto const err = GetLastError( );
        std::cerr << "failed to create test file: " << err;
        return err;
    }

    auto destFilenameLength = wcslen( destFilename );

    auto bufferSize = sizeof( FILE_RENAME_INFO ) + ( destFilenameLength*sizeof( wchar_t ));
    auto buffer = _alloca( bufferSize );
    memset( buffer, 0, bufferSize );

    auto const fri = reinterpret_cast<FILE_RENAME_INFO*>( buffer );
    fri->ReplaceIfExists = TRUE;

    fri->FileNameLength = destFilenameLength;
    wmemcpy( fri->FileName, destFilename, destFilenameLength );

    BOOL res = SetFileInformationByHandle( fileHandle, FileRenameInfo, fri, bufferSize );
    if ( !res )
    {
        auto const err = GetLastError( );
        std::cerr << "failed to rename file: " << err;
        return err;
    }
    else
        std::cout << "success";
}

【讨论】:

  • 感谢您的回答。您如何确定文档包含错误?通过实验,还是您有其他来源?
  • At another site 我的排名略有不同——我想你会发现我对 Windows API 的来龙去脉有一些经验。很明显,关于使用 SetFileInformationByHandle 和 FILE_RENAME_INFO 的文档有些地方不太正确。 FILE_RENAME_INFO 的 FileName 成员是基于 Unicode 的,因此尝试 Unicode 字符的数量是很自然的。
  • 从我的测试看来,FileNameLength 成员似乎被完全忽略了,RootDirectory 句柄似乎是罪魁祸首。我主要是想知道,因为我很高兴了解有关 Windows API 的替代信息来源,MSDN 有时还不够(就像这里一样)。这是您在 StackOverflow 上的第一个答案,在 Gerardo 的回答(包含基本相同的提示)后一小时也让我有点怀疑,我不得不承认 :)
【解决方案2】:

我改变了几个想法:

1) 我不使用根句柄(我将其设置为 NULL)

2) 我更改了您的 FILE_RENAME_INFO 内存分配代码

注意:在 Windows 8 中检查,在同一卷(磁盘)中移动文件

auto const& filepath = L"C:\\remove_tests\\file.txt";
auto const& destpath = L"C:\\remove_tests\\other.txt";
// unclear if that's the "root directory"
auto const& rootdir = L"C:\\remove_tests";

// handles will be leaked but that should be irrelevant here
auto const f_handle = CreateFile(filepath,
    GENERIC_READ | GENERIC_WRITE | DELETE,
      0,
    NULL,
    CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

if (f_handle == INVALID_HANDLE_VALUE)
{
    auto const err = GetLastError();
    std::cerr << "failed to create test file: " << err;
    return err;
}

/*auto const parent_dir_handle = CreateFile(rootdir,
    GENERIC_READ | GENERIC_WRITE | DELETE,
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
    NULL);

if (parent_dir_handle == INVALID_HANDLE_VALUE)
{
    auto const err = GetLastError();
    std::cerr << "failed to get handle to parent directory: " << err;
    return err;
}*/

 auto const destpath_bytes_withOUT_null = _tcslen(destpath);
// unclear if we need to subtract the one wchar_t of FileNameLength:
auto const struct_size = sizeof(FILE_RENAME_INFO) + (destpath_bytes_withOUT_null + 1) * sizeof(WCHAR);
FILE_RENAME_INFO* fri = (FILE_RENAME_INFO*)new BYTE[struct_size];

fri->ReplaceIfExists =  TRUE; // as described by Niall Douglas
fri->RootDirectory = NULL;//parent_dir_handle;
// with or without null terminator?
fri->FileNameLength = destpath_bytes_withOUT_null;// No include null
 _tcscpy_s(fri->FileName, destpath_bytes_withOUT_null + 1, destpath);

BOOL res = SetFileInformationByHandle(f_handle, FileRenameInfo,
                                      fri, struct_size);

 delete fri;
if (!res)
{
    auto const err = GetLastError();
    std::cerr << "failed to rename file: " << err;
    return err;
}
else
    std::cout << "success";

【讨论】:

  • 感谢您的回答。我现在在 Windows 10 下检查了它,它可以工作;其他操作系统的测试将不得不等到星期一。我想 not 使用根句柄将是我尝试的最后一件事......在我的原始源代码中,仅删除根句柄也足以使其工作。 FileNameLength 似乎被忽略了(也可以设置为 0)。 f_handle 似乎只需要 DELETE 权限。
  • 是的,DELETE 只是创建文件句柄时需要的标志,您可以在:msdn.microsoft.com/en-us/library/windows/hardware/… 看到它
  • 我找不到 RootDirectory 必须为 NULL 的任何原因,但我猜:它在内核模式下工作,或者因为 FILE_RENAME_INFO 是为 SetFileInformationByHandle、NtSetInformationFile 和 ZwSetInformationFile 共享的,也许使用 RootDirectory 有一些意义!=其他函数为NULL
  • 哇,它说明了为什么在您链接的描述中需要RootDirectory == NULL。我没有看到这一点,因为我是从SetFileInformationByHandle 导航的,您最终会到达FILE_RENAME_INFO 结构而不是您链接到的FILE_RENAME_INFORMATION 结构。非常感谢!
  • Non-null RootDirectory 可以很好地用于相对/无种族重命名,但系统中的任何HANDLE 都不能在具有DELETE 权限的情况下在该目录上打开。是的,这很糟糕。但事实就是如此。
猜你喜欢
  • 2022-01-15
  • 2011-02-26
  • 2018-10-07
  • 2020-07-19
  • 2018-04-28
  • 2012-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多