目录
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
#include
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
#include
using namesapce std;
int main(){
ifstream ifs;
ifs.open("temp.txt");
//打开后判断文件是否为空
if(ifs.eof());
string name;
int age;
ifs>>name>>age; //空格符会自动跳过
cout<<"姓名:"<
3.二进制方式写文件
#include
#include
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
#include
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<
5.按指定格式读写数据stringstream
#include
#include
#include
//按指定格式写文件
void funWrite(){
string name="凌云志";
int age 18;
ofstream ofs;
ofs.open("temp.txt");
stringstream s;
s<<"姓名:"<
#include#include using namesapce std; int main(){ ifstream ifs; ifs.open("temp.txt"); //打开后判断文件是否为空 if(ifs.eof()); string name; int age; ifs>>name>>age; //空格符会自动跳过 cout<<"姓名:"< 3.二进制方式写文件
#include#include 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#include 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< 5.按指定格式读写数据stringstream
#include#include #include //按指定格式写文件 void funWrite(){ string name="凌云志"; int age 18; ofstream ofs; ofs.open("temp.txt"); stringstream s; s<<"姓名:"<



