fstream

Class fstream

fstream = read + write file stream

#include <fstream>
#include <iostream>

using namespace std;
  • 1.Open file (read + write)
fstream fs("test.txt", ios::in | ios::out);
  • 2.Open mode (important)
mode remark
ios::in read
ios::out write
ios::app append write
ios::trunc open and clean the file (default)
ios::binary binary mode
ios::ate jump to the end of file when open it

// Read and write (It doesn't clean the file)
fstream fs("test.txt", ios::in | ios::out);

// Read and write (Will create file if it's not exists)
fstream fs("test.txt", ios::in | ios::out | ios::trunc);

// Append writing
fstream fs("test.txt", ios::out | ios::app);

// Binary read and write
fstream fs("test.bin", ios::out | ios::in | ios::binary);
  • 3.Using seekg/seekp to mode read/write position
Action remark
Move read pointer fs.seekg(offset, whence)
Move write pointer fs.seekp(offset, whence)
Move all fs.seekg(pos); fs.seekp(pos);

fs.seekg(0); // Move to head of file (read)
fs.seekg(0); // Move to head of file (write)

whence:

- ios::beg // start
- ios::cur // current pos
- ios::end // end of file
    1. Example
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
  fstream fs("test.txt", ios::in | ios::out | ios::trunc);

  if (!fs) {
    cout << "打开文件失败" << endl;
    return 0;
  }

  fs << "Hello World\n";

  string line;
  while(getline(fs, line)) {
    cout << line << endl;
  }

  fs.close();
}