标准C++ 文件操作学习笔记

C++输入/输出标准库 iostream:

  1. istream 输入流
  2. ostream 输出流
  3. iostream 输入/输出流,由上述两个类派生而得;
    而iostream库中包含的主要头文件就包含fstream;

对文件操作主要设计以下3类

  1. ifstream 文件读(输入)操作类
  2. ofstream 文件写(输出)操作类
  3. fstream 文件读(输入)/写(输出)操作类

ifstream

#include <iostream>
#include <string>
#include <fstream>  //ifstream

using namespace std;

int main(){
    //对文件进行读(输入)操作
    ifstream ifd("text1.txt", ios::in);
    if(!ifd.is_open()){
    	cout << "Error: open() " << endl;
    	exit(1);
    }
    string str = "";
    while(getline(ifd, str)){//以行为单位从文件流中读取文件,放入str中
        cout << str << endl;
    }
    cout << endl;
	ifd.close();	//打开文件后,一定要记得关闭
    exit(0);
}

ofstream

#include <iostream>
#include <string>
#include <fstream>  //ofstream

using namespace std;

int main(){
    //对文件进行写(输出)操作
    ofstream ofd("text2.txt", ios::out | ios::trunc);
    if(!ofd.is_open()){
    	cout << "Error: open() " << endl;
    	exit(1);
    }
    string str1 = "hello, world";
    for(auto x : str1){
        ofd << x; 
    } 
    ofd.close();	//打开文件后一定要记得关闭
    cout << endl;

    exit(0);
}

fstream

先写后读
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    //read file
    fstream fd("text1.txt", ios::in | ios::out | ios::app);
    if(!fd.is_open()){
        cout << "error: open()" << endl;
        exit(1);
    }
	//先写
    string str1 = "\nline4:lalala";
    fd << str1;
    //重置文件流指针到文件首
    fd.seekg(fd.beg);
    //读文件内容
    string str = "";
    while(getline(fd, str)){
        //从文件流中读取数据放入str中,每次循环会刷新str
        if(str.size() == 0) cout << '\n';   //读到空格自动换行
        cout << str;
    }
    
    fd.close();
    exit(0);
}
先读后写

在实际中,需要对一个txt文件先读后写,这时可以使用fstream对象、 然后使用流对象的定位函数。seekg,seekp,tellg,tellp来进行相应位置的写。

注意: 在先读后写时,读完这个文件需要对流进行clear操作,否则无法写入。
fstream fd(“text1.txt”, ios::in | ios::out | ios::app);
相当于:
fstream fd;
fd.open(“text1.txt”, ios::in | ios::out | ios::app);

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    //read file
    fstream fd("text1.txt", ios::in | ios::out | ios::app);
    if(!fd.is_open()){
        cout << "error: open()" << endl;
        exit(1);
    }
    string str = "";
    while(getline(fd, str)){
        //从文件流中读取数据放入str中,每次循环会刷新str
        if(str.size() == 0) cout << '\n';   //读到空格自动换行
        cout << str;
    }
    //由于读操作已经读到了文件的末尾,这时输入流标记为文件结束
    //若不清空流标记clear()的话,写操作是写不进去的
    //streampos pos = fd.tellg();
    //fd.seekg(fd.end);
    fd.clear();	
    string str1 = "\nline7:lalala";
    fd << str1;
    fd.close();

    exit(0);
}```

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值