如何在 C++ 中将文件从 ext4 文件系统重命名为 ntfs 文件系统

How to rename a file from ext4 file system to ntfs file system in C++

有疑问。我总是使用 C++ 中的代码(如下)将文件从一个位置移动到同一驱动器中的另一个位置(称之为驱动器)

rename(const char* old_filename, const char* new_filename);

最近需要修改代码将其移动到另一个驱动器(调用B驱动器)。它不起作用,但我可以编写代码写入该特定驱动器(B 驱动器)。在调查中,我发现我生成结果(旧文件)的驱动器(A 驱动器)在 ext4 文件系统中,但我writing/moving 的驱动器在 NTFS(fuseblk)

我如何修改我的代码以将文件移动到 NTFS。我在 ubuntu

中使用 C++

此致

-------------------------------------------- ----------------------

接听用户 4581301 的电话后进行新编辑

这是我写的代码

int main()
{
    std::string dirinADrive = "/home/akaa/data/test3/test_from.txt";                            // this is the parent directory
    std::string dirinBDrive = "/media/akaa/Data/GIRO_repo/working/data/test5/test_to.txt";    // this is where i want to write to
    std::string dirinCDrive = "/home/akaa/data/test3/test_to.txt";                          // this is where i want to write to
    std::string dirinDDrive = "/media/akaa/Data/GIRO_repo/working/data/test5/test_to_write.txt";

    bool ok1{std::ofstream(dirinADrive).put('a')}; // create and write to file
    bool ok2{std::ofstream(dirinDDrive).put('b')}; // create and write to file
    if (!(ok1 && ok2))
    {
       std::perror("Error creating from.txt");
       return 1;
    }

    if (std::rename(dirinADrive.c_str(), dirinCDrive.c_str()))   // moving file to same drive
    {
        std::perror("Error renaming local");
        return 1;
    }


    if (std::rename(dirinADrive.c_str(), dirinBDrive.c_str()))   // moving file to other drive
    {
        std::perror("Error renaming other");
        return 1;
    }

    std::cout << std::ifstream(dirinBDrive).rdbuf() << '\n'; // print file
}

我遇到了一个错误

Error renaming other: Invalid cross-device link

那么什么是跨设备无效link??

谢谢

您不能跨文件系统使用 rename,因为必须复制数据(即使没有原子性问题,让单个系统调用执行任意数量的工作也是有问题的)。您确实必须打开源文件和目标文件,并将一个文件的内容写入另一个文件。应用您想要保留的任何属性(例如,使用statchmod),然后根据需要删除源文件。

在 C++17 中,其中大部分已打包为 std::filesystem::copy_file。 (也有std::filesystem::rename,但在这种情况下并不比std::rename好。)