标准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);
}```

发布了12 篇原创文章 · 获赞 9 · 访问量 332

猜你喜欢

转载自blog.csdn.net/weixin_43547522/article/details/105344888