C++文件操作

//---fstream和文件打开模式---
//--使用ofstream写数据,用ifstream读数据。
//--若程序需要使用同一个流进行输入又进行输出,那么使用fstream很方便。

//-------文件模式---------
//      ios::in      打开一个文件用于输入 
//      ios::out     打开一个文件用于输出 
//      ios::app     所有输出数据附加于文件末尾  
//      ios::ate     打开一个文件用于输出 若文件已存在,移动到文件末尾数据可写入文件任何位置 
//      ios::truct   文件存在,丢弃文件内容(ios::out的默认方式) 
//      ios::binary  打开一个文件用于二进制输入输出 

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	fstream inout;
	//以写的方式打开一个文件 
	inout.open("sayhi.txt",ios::out);
	inout <<"Hi,boy,long time no see,how are you?\n";
	inout.close();
	//以追加的方式打开一个文件 
	inout.open("sayhi.txt",ios::out|ios::app);
	inout<<"Hey,girl,nice to meet you,I am fine,and you?";
	inout.close();
	char hello[20];
	//以读的方式打开一个文件 
	inout.open("sayhi.txt",ios::in);
	while(!inout.eof())
	{
		inout>>hello;
		cout<<hello<<" ";
	}
	inout.close();
	return 0;
} 

  

对于二进制文件的读取:

//为了读写二进制文件,必须对流对象使用read和write函数

//向文件中写入非字符数据,用reinterpret_cast<dataType>(address)
//将非字符地址转换为二进制I/O需要的字符数组指针。 
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	fstream binaryio;
	binaryio.open("city.dat",ios::out|ios::binary);
	if(binaryio.fail())
	{
		cout<<"you fail the city";
	} 
	char s[]="helloworld";
	binaryio.write(s,10);
    binaryio.close();
	binaryio.open("city.dat",ios::in|ios::binary); 
	char temp[10];
	binaryio.read(temp,10);
	temp[10]='\0';
	cout<<s;
	binaryio.close();
	return 0;
}

  

原文地址:https://www.cnblogs.com/xrong/p/2968502.html