l10_11.cpp

来自「《C++程序设计教程》电子教案及例题源码」· C++ 代码 · 共 30 行

CPP
30
字号
#include<fstream.h>
#include<iostream.h>
void main()
{
	fstream  iofile( "E:\\myfile.txt", ios::in | ios::app ); //打开文件读写,在末尾添加数据
	iofile.seekg( 0, ios::end );                 //定位至文件尾
	streampos  lof= iofile.tellg();             //获取文件长度
	char *data;
	data = new char[lof];                    //动态分配内存用于保存文件内容
	iofile.seekg( 0, ios::beg );                //定位至文件头
	iofile.read( data, lof );                   //将文件内容读到data指向的内存中
	cout << "原文件内容为:" << endl;
	for( int i =0; i<lof; i++ )
		cout << data[i];                    //逐个输出data指向内存中的字符
	cout << endl;
	iofile.write( data, lof );                  //将读出内容写入文件尾
	delete [] data;
	iofile.seekg( 0, ios::end );   
	lof = iofile.tellg();
	data = new char[lof];
	iofile.seekg( 0, ios::beg );
	iofile.read( data, lof );
	cout << "读写操作后文件内容为:" << endl;
	for(i =0; i<lof; i++ )
		cout << data[i];
	cout << endl;
	iofile.close();
	delete [] data;
}

⌨️ 快捷键说明

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