目錄
1.寫文本檔案
2.讀文本檔案
3.二進制方式寫檔案
4.二進制讀檔案
5.按指定格式讀寫資料stringstream
對檔案流的讀寫
ifstream 對檔案輸入(讀檔案)
ofstream 對檔案輸出(寫檔案)
fstream 對檔案輸入或輸出
檔案打開方式:
| ios::in | 讀方式打開檔案 |
| ios::out | 寫方式打開檔案 |
| ios::trunc | 如果此檔案已經存在, 就會打開檔案之前把檔案長度截斷為0 |
| ios::app | 尾部最加方式(在尾部寫入) |
| ios::ate | 檔案打開后, 定位到檔案尾 |
| ios::binary | 二進制方式(默認是文本方式) |
現在源程式同一目錄下有”temp.txt“檔案,檔案內容為“凌云志”+空格+18(18為int型別)
1.寫文本檔案
#include<fstream>
#include<iostream>
using namesapce std;
int main(){
ofstream ofs; //也可以使用fstream ,但是fstream默認打開方式不截斷檔案長度
//ofstream 的默認打開方式是截斷式寫入 ios::out|ios::trunc
//fstream 的默認打開方式是截斷寫入 ios::out
//建議指定打開方式
ofs . open("temp.txt",ios::out|ios::trunc);
ofs<<"凌云志"<<" "<<18<<'\t';
ofs.close();
return 0;
}
2.讀文本檔案
#include<fstream>
#include<iostream>
using namesapce std;
int main(){
ifstream ifs;
ifs.open("temp.txt");
//打開后判斷檔案是否為空
if(ifs.eof());
string name;
int age;
ifs>>name>>age; //空格符會自動跳過
cout<<"姓名:"<<name<<"年齡:"<<age<<endl;
ifs.close();
return 0;
}
3.二進制方式寫檔案
#include<fstream>
#include<iostream>
using namesapce std;
int main()
{
string name = "凌云志";
int age = 18 ;
ofstream outfile;
//.dat檔案用記事本打開會是亂碼
outfile.open("user.dat", ios::out | ios::trunc | ios::binary);
outfile << name << "\t";
//outfile << age << endl; //會自動轉成文本(字串)方式寫入
outfile.write((char*)&age, sizeof(age)); //將age的地址轉為char指標型別
// 關閉打開的檔案
outfile.close();
system("pause");
return 0;
}
4.二進制讀檔案
#include<fstream>
#include<iostream>
using namesapce std;
int main(){
ifstream ifs;
ifs.open("temp.text",ios::in|ios::binary);
if(ifs.eof()){return;}
string name;
int age;
//ifs>>age; temp是二進制存盤,直接讀取會以文本方式讀出
//使用read讀取會讀取空格符\制表符.....
//ifs.read((char*)&age,sizeof(age));
//正確讀取方式
ifs>>name; //讀取姓名
char ch;
ifs.read((char*)&ch,sizeof(ch)); //讀取空格
ifs.read((char*)&age,sizeof(age)); //讀取年齡
cout<<name<<age<<endl;
cout<<temp<<endl;
}
5.按指定格式讀寫資料stringstream
#include<fstream>
#include<string>
#include<sstream>
//按指定格式寫檔案
void funWrite(){
string name="凌云志";
int age 18;
ofstream ofs;
ofs.open("temp.txt");
stringstream s;
s<<"姓名:"<<name<<"\t\t年齡:"<<age<<endl;
//把指定格式資料寫入檔案
ofs<<s.str();
ofs.close();
}
//按指定格式讀檔案
void funRead(){
ifstream ifs;
ifs.open("temp.txt");
string line;
char name[32];
int age;
while(1){
if(ifs.eof()){break;}
getline(ifs,line); //每次讀取一行
//按C語言格式將讀取的一行轉為char*陣列格式(line.c_str())
sscanf_s(line.c_str(),"姓名:%s 年齡:%d",name,sizeof(name),&age);
cout<<"姓名:"<<name<<"\t\t年齡:"<<age<<endl;
}
}
int main(){
funWrite();
funRead();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/333828.html
標籤:其他
上一篇:如何防止JColorChooser吸收JComponent上的KeyEvent?
下一篇:【Android 逆向】selinux 行程保護 ( selinux 行程保護 | 寬容模式 Permissive | 強制模式 Enforcing )


