C++中的文件和流

所需頭文件:ios

#include<iostream>
#include<fstream>

標準庫fstream中定義了三種新的數據類型:app

  • ofstream
    表示輸出文件流,用於建立文件並向文件寫入信息
  • ifstream
    表示輸入文件流,用於從文件讀取信息
  • fstream
    同時具備上面了兩種數據類型的功能,能夠建立文件,向文件寫入信息,從文件讀取信息

打開文件

從文件中讀取信息或者向文件寫入信息以前,必須先打開文件。函數

void open(const char *filename,ios::openmode mode);
//open()函數是fstream、ifstream、ofstream對象的一個成員

open()函數第二個參數定義文件被打開的模式,模式有一下幾種:spa

  • ios::app
    追加模式,全部寫入都追加到文件末尾
  • ios:ate
    文件打開後定位到文件末尾
  • ios::in
    打開文件用於讀取
  • ios::out
    打開文件用於寫入
  • ios::trunc
    若是該文件已經存在,其內容將在打開文件以前被截斷,
    即將文件長度設爲0

能夠把上面的幾種模式混合使用,好比,想以寫入的模式打開文件,而且但願截斷文件,以防止文件已經存在,能夠用下面的寫法:code

ofstream afile;
afile.open("file.dat",ios::out | ios::trunc);

關閉文件

當C++程序終止時,會自動關閉刷新全部流,釋放全部分配的內存,並關閉全部打開的文件。可是爲了防止內存泄露,應該手動釋放使用完畢的流資源。對象

void close();
//close()是fstream,ifstream,ofstream對象的一個成員

寫入/讀取文件

用流插入運算符<<向文件寫入信息,就像使用該運算符輸出信息到屏幕上同樣
用流提取運算符>>從文件讀取信息,就像使用該運算符從鍵盤輸入信息同樣內存

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

int main(int argc, char const *argv[])
{
	/* code */
	char data[100];

	ofstream  outfile;
	outfile.open("afile.txt");

	cout<<"Writing to the file"<<endl;
	cout<<"Enter your name:";
	cin.getline(data,100);

	outfile<<data<<endl;

	cout<<"Enter your age:";
	cin>>data;
	cin.ignore();//ignore()會忽略掉以前讀語句留下的多餘字符

	outfile<<data<<endl;

	outfile.close();

	ifstream infile;
	infile.open("afile.txt");

	cout<<"Reading from file"<<endl;
	infile>>data;
	cout<<data<<endl;

	infile>>data;
	cout<<data<<endl;

	infile>>data;
	cout<<data<<endl;

	infile.close();

	return 0;
}
//這個程序有一個問題:輸入的字符串中不能包含空白字符
相關文章
相關標籤/搜索