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

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

本文关键字:文件系统 ext4 重命名 命名为 ntfs 文件 C++      更新时间:2023-10-16

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

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

最近我需要修改代码以将其移动到另一个驱动器(调用 B-Drive(。它不起作用,但我可以编写代码以写入该特定驱动器(B 驱动器(。经过调查,我发现我产生结果(旧文件(的驱动器(A 驱动器(在 ext4 文件系统中,但我正在写入/移动到的驱动器在 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

那么什么是无效的跨设备链接?

谢谢

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

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