demo_5_file_dat_2.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 52 行

CPP
52
字号

//***************************************************
// 随机访问二进制数据文件
//***************************************************

# include <fstream.h>
# include <stdlib.h>

int main()
{
	fstream file;

	file.open("test.dat",ios::in|ios::out|ios::binary);

	if(!file)
	{
		cerr<<"open error!"<<endl;
		exit(1);
	}

	file<<"AB CD EF"<<endl;

	cout<<file.tellg()<<endl;
	file.seekg(0);           //非常关键
//	file.seekg(0,ios::beg); 
	cout<<file.tellg()<<endl;

	char ch;

	while(!file.eof())
	{
		file.get(ch);
		if(ch==' ') 
		{
			cout<<file.tellg()<<" ";
			file.get(ch); //读入一个字符,并且文件读指针前移sizeof(ch)
			cout<<file.tellg()<<" ";
			cout<<ch<<endl;
		}
	}
	
	file.close();
	
	return 0;
}

/*
9
0
3 4 C
6 7 E
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?