c++ fstream read()函数不起作用

标签 c++

为什么我的以下代码无法从文件中读取单个整数? 它显示“fail() reading”后跟“0”。

在 linux ubuntu gcc 编译器上。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream fout2("int_data",ios::binary|ios::out);
    int a = 2;
    fout2.write((char*)&a,sizeof(a));
    int b=0;
    ifstream fin2("int_data",ios::binary|ios::in);
    fin2.read((char*)&b,sizeof(b));
    if(fin2.fail())
        cout << "fail() reading" << endl;
    cout << b << endl;
}

最佳答案

这可能会因为几个原因而失败:

  1. 您的操作系统可能会阻止您打开当前打开用于写入的文件
  2. 您可能还没有将数据写入文件

您可以使用 close 解决这两个问题在构造 fin2 之前:

ofstream fout2("int_data", ios::binary);
const int a = 2;

fout2.write(reinterpret_cast<const char*>(&a), sizeof(a));
fout2.close();

int b = 0;
ifstream fin2("int_data", ios::binary);

if(!fin2.read(reinterpret_cast<char*>(&b), sizeof(b))) {
    cout << "fail() reading" << endl;
}
cout << b << endl;;

Live Example

关于c++ fstream read()函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37272768/

相关文章:

c++ - 最新的 Visual Studio 2005 安全更新是否会在热修复客户站点时导致 C 运行时库问题

C++ operator<< gtest AssertionFailure 编译错误

c++ - Windows GDI 上下文 - LoadImage

c++ - 如何摆脱打开文件中的 ""

c++ - 投影和 View 矩阵

python - ZMQ Python PUB/SUB 可以工作,但我的 C++ Subscriber with Python Publisher 不行

c++ - 分配给函数调用返回的指针

c++ - 多CPU多线程中的多线程

c++ - bool 变量通常是作为单个位实现的吗?

c++ - std::unordered_map:渐近 {search,insert,remove} 在键的大小和数据类型方面的表现