【文件读入】c++ ifstream read函数怎么读入文件中的整数?

一葉孤星坠空城丶 2015-10-17 09:12:50

#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;


const int DATA_NUM = 100; // 文件中数据量
const int BUFFER_SIZE = 15; // 缓冲区大小
int g_inputBuffer[BUFFER_SIZE]; // 输入缓冲区
int g_ouputBuffer[BUFFER_SIZE]; // 输出缓冲区



void createData()
{
ofstream file_out("data");

srand((unsigned)time(0));
// 生成DATA_NUM个1000以内的随机整数写入文件中
for(int i = 1; i <= DATA_NUM; i++)
{
int data = rand() % 1000;
file_out << data << endl;
}
file_out.close();
}

void readData()
{
ifstream file_in("data",ios::binary);
while(!file_in.eof())
{
file_in.read((char*)g_inputBuffer, sizeof(int) * BUFFER_SIZE); // 用二进制方式读入文件,读入的大小是整个缓冲区的大小
int count = file_in.gcount(); // 读入的字节数?
cout << "读入的数量 : " << count << endl;

for (int i = 0 ; i < count ; i++)
cout << g_inputBuffer[i] << " ";
cout << endl;
}
file_in.close();
}

int main()
{

createData();
readData();
return 0;

}


输出的整数根本错乱了,请问怎样才能正确实现我想要的功能?
...全文
721 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
谢谢提醒。我用write写入再读出,结果就正确了。

void createData()
{
	ofstream file_out("data");

	srand((unsigned)time(0));
	cout << "随机数 : ";
	for(int i = 1; i <= DATA_NUM; i++)
	{
		int data = rand() % 1000;
		cout << data << " ";
		file_out.write((char*)(&data),sizeof(int));
	}
	cout << endl;
	file_out.close();
}

void readData()
{
	ifstream file_in("data",ios::binary);
	while(!file_in.eof())
	{
		file_in.read((char*)g_inputBuffer, sizeof(int) * BUFFER_SIZE);
		int count = file_in.gcount() / sizeof(int);
		cout << "读入的数量 : " << count << endl;


		for (int i = 0 ; i < count ; i++)
			cout << g_inputBuffer[i] << " ";
		cout << endl;
	}
	file_in.close();
}
fefe82 2015-10-17
  • 打赏
  • 举报
回复
read write 是二进制读写 << >> 是格式化读写 有关 << 写 read 读当然错乱了。 写的时候用 write 吧。

64,439

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧