C++Primer文件讀寫

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

int main()
{
	//---------------------按行寫文件-----------------------------
	//打開文件用於寫,若文件不存在,則創建它,若已存在,則清空原內容
	//注意路徑名中的斜槓要雙寫
	//	ofstream file("C:\\Users\\桑海\\Desktop\\HelloWord\\HelloWord.txt", ios::app);		//以app方式打開,在文件尾寫入
	//作用同上
	string str;
	cout << "Enter the name of the file:" << endl;
	cin >> str;		//enter the name of the file you want to open
	ofstream file(str.c_str(), ios::app);		//open file named "str" for writing
	// check that the open succeeded
	if(!file)	//error: warn the user; bail out!
	{
		cerr << "error: unable to open input file: " << file << endl;
		return -1;
	}
	//string str;
	while(getline(cin, str))		//write
		file << setw(20) << str << endl;
	file.close();		//close file when we're done with it
	file.clear();
	//---------------------按行讀文件-----------------------------
	ifstream file2("C:\\Users\\桑海\\Desktop\\HelloWord\\HelloWord.txt");
	while(!file2.eof())
	{
		getline(file2, str);
		cout << setw(20) << str << endl;
	}
	file2.close();		//close file when we're done with it
	file2.clear();		//reset state to ok
	return 0;
}

文件模式:
in 							打開文件做讀操作(若文件不存在則創建,文件不存在則創建(ifstream默認的打開方式)
out 							打開文件做寫操作(文件不存在則創建,若文件已存在則清空原內容,ofstream默認的打開方式)
app 						在每次寫之前找到文件尾,即:總是在原文件尾寫入操作(文件不存在則創建)
ate 							打開文件後立即將文件定位在文件尾,可改變定位位置
trunc 						打開文件時清空以存在的文件流
binary 						以二進制模式進行IO操作

打開文件的方法
調用構造函數時指定文件名和打開模式
ifstream f("d:\\12.txt",ios::nocreate);     //默認以 ios::in 的方式打開文件,文件不存在時操作失敗
ofstream f("d:\\12.txt");            		//默認以 ios::out的方式打開文件
fstream f("d:\\12.dat",ios::in|ios::out|ios::binary); //以讀寫方式打開二進制文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章