c++ - 写入 ofstream 然后用 ifstream 读取不会读取整个文件

标签 c++ ifstream ofstream

以下程序写入 100 个字节,但没有将它们全部读回。为什么?

#include <iostream>
#include <random>
#include <vector>
#include <climits>
#include <algorithm>
#include <map>
#include <fstream>
#include <iomanip>

int main()
{
    constexpr size_t file_size{100};
    std::random_device r{};
    auto min = std::numeric_limits<unsigned char>::min();
    auto max = std::numeric_limits<unsigned char>::max();
    std::uniform_int_distribution<size_t> ud{min,max};

    {
        std::ofstream ofs{"otp.bin",std::ios::binary};
        for(size_t i{}; i < file_size; ++i) {
            ofs << static_cast<unsigned char>(ud(r));
        }
        ofs.close(); // not needed? 
    }

    std::ifstream ifs{"otp.bin",std::ios::binary};

    unsigned char c{};
    size_t i{};
    while(ifs >> c) {
        std::cout << std::setw(4) << std::hex << static_cast<unsigned int>(c) << std::dec << ((++i % 10 == 0) ? '\n' : ' ');
    }

    std::cout << '\n' << i << " bytes read.\n";
    return 0;
}

我有时会得到 99、94、96,但从来没有得到 100。我在 VS2015、clang 和 gcc 上遇到了这种行为。

Here是在线示例。

最佳答案

ifs >> c

默认跳过空格。放

ifs >> std::noskipws;

在循环之前也读取空白字节。


还有

ofs.close(); // not needed? 

确实不需要,当流超出范围时文件将关闭。

关于c++ - 写入 ofstream 然后用 ifstream 读取不会读取整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445031/

相关文章:

c++ - 阻止从 std::ifstream 读取

c++ - 我如何在 C++ 的子目录中创建文件?

c++ - ofstream 名称中的变量

c++ - 如何从 fgets 读取整个整数流并推回一维 vector ?

c++ - 在 C++ 中,如何提取文本文件的 ExtractFilePath

C++:如何将 'PCZZWSTR' 类型更改为 'char',反之亦然?

c++ - 将 std::wstring 转换为 int

c++ - (C++) noob - 我的代码有什么问题?

c++ - std::ofstream 是可移动的吗?

c++ - 将 static_cast 与 boost::bind 结合使用