输入输出文件

输出程序数据到文件的步骤有五个:

(1)包含头文件fstream

(2)定义ofstream对象,

(3);利用ofstream对象与要写入的文件进行关联

(4)就像利用cout对象一样将要写入的数据写到文件中

(5)关闭文件对象

例程如下:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream ocout;
	//打开指定路径的文件
	ocout.open("E:\\2.doc");
	ocout<<"asdfawefewrfwaefwae"<<endl;
	ocout.close();
	return 0;

}


fstream并不能完全代替iostream,ofstream只继承了部分iostream的函数。fstream没哟全局输出对象,在使用时必须手动创建,而iostream中则可以直接使用cout对象。

读取文件中的数据的步骤跟写入文件数据是一样的,见如下例程:

 

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream ocout;
	//打开指定路径的文件
	ocout.open("1.doc");
	ocout<<"asdfawefewrfwaefwae"<<endl;
	ocout.close();
	ifstream icin;
	icin.open("1.txt");
	char temp[30];
	icin>>temp;
	cout<<temp<<endl;
	icin.close();
	return 0;

}


 

你可能感兴趣的:(iostream)