C++文件流

文件读写是几乎所有开发语言中比较基础和重要的应用,C++作为跨平台语言,提供了以流为媒介的操作接口,可以非常方便地实现各类文件的读写。

fstream类

C++中文件读写的主要接口类是fsteam类,fstream类包含在头文件中,继承自iostream

类似于iostreamostreamistream的关系,C++中还有ifstreamofstream类,分别实现文件的读和写,注意ifstream继承自istreamofstream继承自ostream;使用方式和fstream基本一致,因此本文重点讨论fstream

fstream对象内部维护了一个filebuf对象,作为流缓冲区,用来暂存文件从物理存储设备读取之后或写入之前的内容;filebuf与物理存储上的文件关联的方式是调用fstreamopen操作;一旦filebuf与物理文件关联之后,对filebuf的任何操作等同于对物理文件的操作。

fstream的构造函数有两种形式,分别为默认的不带参的构造函数,以及带参数(filename,openmode)的构造函数;调用带参数的构造函数时,构造的同时会关联文件,从而不用调用open操作。

fstream();  
explicit fstream (const char* filename,
                  ios_base::openmode mode = ios_base::in | ios_base::out);

打开/关闭文件

  • 关联(打开)文件 -- open,open操作带两个输入参数
    • const char* filename -- 文件名
    • ios_base::openmode mode -- 关联模式

open操作内部实际是调用rdbuf(一个指向内部filebuf对象的指针);如果fstream已经关联到某个文件,再次调用open将会失败;

简单说一下openmode,6种模式,可以组合使用:

模式 解释 说明
in input 只读
out output 只写
binary binary 文件以二进制方式操作,而非文本方式
ate at end 定位到文件结尾,写操作将会清空原文件
app append 写文件操作从文件结尾开始,追加内容
trunc truncate 文件原有内容将会被忽略,即覆盖原文件

其中,容易误解的是ate和app,它们的区别可以参考ios::app与ios::ate的区别

文件是否关联(打开)成功,可以通过is_open来判断;

  • 关闭文件 -- close,读写操作完成后,需要取消文件关联;

写文件

与写操作相关的函数:

  • put
    put是向文件中写入字符,函数原型:ostream& put (char c);
  • write
    write是向文件中写入字符串,函数原型:ostream& write (const char* s, streamsize n);
  • <<操作符
    <<向文件写内容和像cout写操作相同,非常简单易用;

写文件示例:

#include 
#include 

int main(int argc, char** argv) {
    std::ofstream ofs("test.txt");
    std::string new_content = "pine_apple water_melon ";
    ofs.write(new_content.c_str(), new_content.size());
    ofs << "blue_berry" << std::endl;
    ofs.put('l');
    ofs.put('e');
    ofs.put('m');
    ofs.put('o');
    ofs.put('n');

    ofs.close();
}

写入后的文件内容:

pine_apple water_melon blue_berry
lemon

读文件

  • 读文件(针对文本文件)的一种方式是:
    • 先获取文件长度,可以配合使用seekgtellg函数,seekg(streamoff off, ios_base::seekdir way)可实现相对于某位置,去移动下一个字符指针的偏移位置,最常用的是seekg(0, ios_base::end)seekg(0, ios_base::beg),从而将指针位置移动到文件结尾或开始;tellg()返回当前字符在文件流中的位置;可以先将指针移动到结尾,然后获取结尾字符的位置作为文件长度,最后再将指针移动回开始的位置;
    • 将文件内容全部或部分读取,或者循环遍历读取字符或字符串;读文件可调用read操作,read可返回任意个数的字符到字符数组中,所以需要输入2个参数,char* sstreamsize n;

附带一个读文件的demo实例(来自http://www.cplusplus.com/reference/istream/istream/read/)

// read a file into memory
#include      // std::cout
#include       // std::ifstream

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    // ...buffer contains the entire file...

    delete[] buffer;
  }
  return 0;
}

读文件除了采用read函数以外,还有多种方式,比如getline函数,可以获取每一行的内容,默认的分隔符是'\n',也可以通过参数设置分隔符;
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

  • 另一种读文件方式 -- 迭代器来读取文件:
    istream_iterator可以从输入流中连续读取元素,一般以空格作为分割,可以像普通迭代器一样遍历文本文件,也可以直接将字符串读入vector容器中。

代码示例:

#include 
#include 
#include 
#include 
 
int main()
{
    std::ifstream ifs("test.txt");
    std::istream_iterator iit(ifs);
    std::istream_iterator eos;
    std::vector vec(iit, eos);
    std::cout << "vec size: " << vec.size() << std::endl;
    for(size_t i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;
    ifs.close();
   
    return 0;
}

二进制文件读写

二进制文件的读写与文本文件读写本质上是一致的,只不过在关联文件的时候,应当组合std::ios::binary模式;以下给出一个简单的示例:

  • 向一个二进制文件写入0~9共9个数字:
#include 
#include 

int main(int argc, char** argv) {
    std::ofstream ofs("bin_test", std::ios::out | std::ios::binary);
    
    for(size_t i = 0; i < 10; ++i) {
        ofs.put(char(i));
    }

    ofs.close();
}
  • 读入刚才写的二进制文件
#include 
#include 
#include 

int main(int argc, char** argv) {
    std::ifstream ifs("bin_test", std::ios::in | std::ios::binary);
    
    // get file content lenth
    ifs.seekg(0, ifs.end);
    int len = ifs.tellg();
    ifs.seekg(0, ifs.beg);

    // read data
    char* data = new char[len];
    ifs.read(data, 10);
    for(size_t i = 0; i < len; ++i) {
        std::cout << (int)(data[i]) << std::endl;
    }

    ifs.close();
    delete[] data;
}

你可能感兴趣的:(C++文件流)