C++文件流

2018-11-14  本文已影响0人  wywindz

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

fstream类

C++中文件读写的主要接口类是fsteam类,fstream类包含在头文件<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操作内部实际是调用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来判断;

写文件

与写操作相关的函数:

写文件示例:

#include <fstream>
#include <string>

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

读文件

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

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // 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 );

代码示例:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
 
int main()
{
    std::ifstream ifs("test.txt");
    std::istream_iterator<std::string> iit(ifs);
    std::istream_iterator<std::string> eos;
    std::vector<std::string> 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模式;以下给出一个简单的示例:

#include <fstream>
#include <string>

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 <fstream>
#include <string>
#include <iostream>

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;
}
上一篇 下一篇

猜你喜欢

热点阅读