C++文件操作fstream

目录

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;

}