gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:08:47 25 4
gpt4 key购买 nike

以下程序写入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com