C++ -----文件IO

1流的概念

  • 流:數據從一個對象到另一個對象的傳輸。
  • 功能:標準輸入輸出+文件處理

1.1流分類

  • 標準庫定義了三大類流類型:標準I/O流、文件流、字符串流
    在這裏插入圖片描述

2流對象

2.1分類

  • 通常標準I/O流對象是全局對象不需要定義,
  • 而文件流對象和字符串流對象需要用戶定義。
  • 流對象通常都不能複製。
全局流對象 名稱 緩存
cout 標準輸出流 帶緩存
cin 標準輸入流 帶緩存
clog 標準日誌流 帶緩存
cerr 標準錯誤流 無緩存

2.2流對象狀態

流對象狀態在某一個時刻必定處於以下四個狀態之一。

No. 狀態 含義
1 good() 前一個流操作成功
2 eof() 到輸入尾/文件尾
3 fail() 發生意外事情(讀取失敗)
4 bad() 發生意外嚴重事情(磁盤讀取失敗)

2.3標準輸入

2.3.1 成員函數

#include<iostream>
using namespace std;
void test01(){
	char c=cin.get();//一次只能取一個字符
	cout<<"c= "<<c<<endl;//也可以得到換行符 因爲換行符也是一個字符 
	
}
void test02(){
	char buf[1024];
	cin.get(buf,1024);
	char c=cin.get();
	if(c=='\n'){//讀取字符串不會把換行符取走 換行符還遺留在緩衝區
		cout<<"換行符在緩衝區"<<endl;
	}
	cout<<buf<<endl;
	
}
void test03(){
	char buf[1024];
	cin.getline(buf,1024);
	char c=cin.get();
	if(c=='\n'){//讀取字符串把換行符取走 並扔掉 等待下次輸入
		cout<<"換行符在緩衝區"<<endl;
	}
	cout<<buf<<endl;	
}
void test04(){
	cin.ignore(2);//沒有參數代表忽略一個字符 有參數代表N個字符
	char c=cin.get();
	cout<<"c= "<<c<<endl;

}
//cin.peek 偷窺
void test05(){
	char c=cin.peek();//比如:輸入a 然後偷看一眼a 然後將它在放入緩衝區	
	cout<<"c= "<<c<<endl;
	c=cin.get();
	cout<<"c= "<<c<<endl;

}
//cin.putback放回
void test06(){
	char c=cin.get();
	cin.putback(c);//將字符放回緩衝區
	char buf[1024];
	cin.getline(buf,1024);
	cout<<buf<<endl;
}

void test07(){
	//緩衝區標誌類
	cin.clear();//清空標誌位
	cin.sync();//刷新緩衝區
	cout<<cin.fail()<<endl;

}
int main(){
test06();
}

2.4標準輸出

  • 格式化輸出有兩種方法

2.4.1流對象有關的成員函數

在這裏插入圖片描述

  • 參數
    在這裏插入圖片描述
#include<iostream>
#include<iomanip>
using namespace std;//格式化輸出流 使用控制符方式格式化輸出的頭文件

//cout.put
//cout.write
void test1(){
	int num=99;
	cout.width(20);
	cout.fill('*');
	cout.setf(ios::left);
	cout.unsetf(ios::dec);
	cout<<num<<endl;
}

2.4.2控制符方法

在這裏插入圖片描述

void test2(){
	int number=99;
	cout<<setw(20)//設置寬度
	    <<setfill('X')//填充
	    <<hex//16進制
		<<number<<endl;
}
int main(){
	test2();
}

3文件流

在這裏插入圖片描述

#include<iostream>
#include<fstream>//文件讀寫的頭文件
using  namespace std;

//寫文件
void test01(){
	//方式一	
	//ofstream ofs("./text.txt",ios::out|ios::trunc);	
	//方式2
	ofstream ofs;
	ofs.open("./text.txt",ios::out|ios::trunc);	
	if(!ofs.is_open()){
		cout<<"文件打開失敗"<<endl;
	}
	//寫文件
	ofs<<"姓名旅客"<<endl;
	ofs<<endl;
	//關閉流對象
	ofs.close();
}
//讀文件
void test02(){
	ifstream ifs;
	ifs.open("./text.txt",ios::in);	
	if(!ifs.is_open()){
		cout<<"文件打開失敗"<<endl;
		return ;
	}
	
	//第一種方法將每行讀取到緩衝區中 按行讀取 知道讀到文件結尾
	char buf[1024];
	while(ifs>>buf){
		cout<<buf<<endl;
	}
	
	/*
	//第二種方法
	char buf[1024];
	while(!ifs.eof()){
		ifs.getline(buf,sizeof(buf));
	}
	*/
	/*
	//第3種方式單個字符的讀取
	char c;
	while((c=ifs.get())!=EOF){
		cout<<c;
	}
	*/	
	cout<<endl;	
	ifs.close();
}
int main(){
test01();
test02();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章