C++ 打开一个文件并写入文件的任意位置

标签 c++ windows performance io

我需要打开一个现有文件并写入到该文件的任意位置。同样位于可能大于文件当前大小的位置。

每次调用写入操作时,使用“ab” 打开文件会将位置指示器设置为文件末尾 - 这样就不起作用了。

"w+b""wb" 打开文件会导致文件被多次写入(复制?)。 Filesize 多次从 0 开始 - 这需要很长时间。查看执行以下测试(运行 1 次)时发生的情况的视频:http://screencast.com/t/Uj5ymikZUYJ

BOOST_AUTO_TEST_CASE(FileWriteTest_W_PLUS_B) {
    auto started = chrono::high_resolution_clock::now();

    FILE *filePointer = nullptr;
    auto tmpFilename = string("C:\\temp\\") + boost::uuids::to_string(boost::uuids::random_generator()());
    auto bufferSize = 1024 * 1024;

    unique_ptr<unsigned char[]> buffer(new unsigned char[bufferSize]);
    RAND_bytes(buffer.get(), bufferSize);

    for (long long i = 0; i < 5; i++) {
        //Open file
        int openError = fopen_s(&filePointer, tmpFilename.c_str(), "w+b");  
        if (openError != 0)
            BOOST_FAIL(string("Failed to open file ") + tmpFilename);

        auto CurrentPosition = 1024LL * 1024LL * 1024LL * i;

        //Set position to 0/1/2/3/4 GB 
        fsetpos(filePointer, &CurrentPosition);

        //Write 1 GB of data at current position
        for (int n = 0; n < 1024; n++) {
            int written = fwrite(buffer.get(), sizeof(unsigned char), bufferSize, filePointer);
            if (written != bufferSize) {
                BOOST_FAIL(string("Unable to write ") + to_string(bufferSize) + string(" to file ") + tmpFilename + string(" at position ") + to_string(CurrentPosition));
            }
        }

        //Close file
        fclose(filePointer);
    }

    auto ended = chrono::high_resolution_clock::now();
    cout << "Time :" << duration_cast<duration<double>>(ended - started).count() << " seconds";
}

所以我的问题是:有没有什么方法可以打开现有文件并写入任意位置(也可以是大于当前大小的位置)——而不会像我目前使用 时那样受到性能损失“wb”/“w+b”

或者我是否必须将文件设为最终大小 - 第一次写入文件时? (例如 Torrent 客户端似乎就是这样做的)。

fstreams 不是一种选择,因为它们的 I/O 性能很差。 (参见 writing-a-binary-file-in-c-very-fast)

最佳答案

您应该以"r+b" 模式打开流。 "w" 模式导致文件被截断。如果该文件不存在,则必须先使用 "wb" 创建。

但是请注意,fsetpos() 可能无法将当前位置设置到文件末尾之外。您应该检查返回值并根据需要将文件填充到目标位置。

对于作为字节偏移量有意义的位置,流还必须以二进制模式打开,带有 b。默认情况下,流在文本中更多地打开,这在某些系统(例如 Windows)上可能会阻止正确的偏移量管理。

关于C++ 打开一个文件并写入文件的任意位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080952/

相关文章:

python - 如何将一些字符串粘贴到 Python 中的事件窗口?

javascript - 如果 JQuery 的 .find() 比 .filter() 更快?

C++:函数在数组的第 4 个元素处崩溃

c++ - 尝试(但失败)在 Windows 10 的 64 位 Ubuntu 上运行 Hello World 32 位 C++ 程序

c++ - 在 C++ 中显示、更新和验证枚举值

windows - 如何在文件移动过程中移动文件并删除文件名中的连字符?

c++ - 如何有效地将 std::vector 视为 C 缓冲区?

node.js - 我可以在没有管理员权限的情况下使用 NVM

javascript - JQuery 选择器性能和比较问题

visual-studio - dotnet framework 4 中的字符串比较