C++ 文本IO

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mcl2840072208/article/details/78428314

1.(基本概念)文本的输入输出是以计算机为主角

ifstream 文件输入流,以计算机为主角,将文件输入到计算机。
ofstream 文件输出流,从计算机输出到文件。

2.(简单使用)

模式 含义
ios_base::in 打开文件,以备读取
ios_base::out 打开文件,以备写入
ios_base::ate 打开文件,并移到文件尾
ios_base::trunc 如果文件存在就截取文件
ios_base::app 追加到文件尾(之前的内容不添加其他模式,则之前的内容为只读)
ios_base:: binary 二进制文件

A Simple Example:
ifstream open() 方法第二个参数 默认为ios_base::in
ofstream open() 方法第二个参数 默认为ios_base::out|ios_base::trunc

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

const char * file = "guests.txt";

using namespace std;

int main(void){
    ifstream fin;
    char ch;
    fin.open(file);
    ofstream fout(file,ios::out|ios::app);

    cout << "Enter guest names (enter ablank line to quit)\n";
    string name;
    while(getline(cin,name)&& name.size()>0)
    {
      fout << name<<endl;
    }
    fin.close();
    fout.close();

    fin.clear();
    fin.open(file);
    if(fin.is_open())
    {
      cout<<"Here are the new contents of the "<<file<<" file:\n";
      while (fin.get(ch)) {
        cout<<ch;
      }
      fin.close();
    }
    cout<<"Done.\n";

    return 0;
}

3.随机读取

两个重要函数seekg(), seekp() 读取指针移到指定的位置、输出指针移到指定的位置
模式 含义
ios_base::beg 相对文件开始位置的偏移量
ios_base::cur 相对于当前位置的偏移量

fin.seekg(30,ios_base::beg);//30 bytes beyond the beginning
fin.seekg(-1,ios_base::cur);//back up one byte
fin.seekg(0,ios_base::end);//go to the end of the file
fin.seekg(0);//go to the beginning of the file

猜你喜欢

转载自blog.csdn.net/mcl2840072208/article/details/78428314