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);
| 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 |
fstream fs("test.txt", ios::in | ios::out);
fstream fs("test.txt", ios::in | ios::out | ios::trunc);
fstream fs("test.txt", ios::out | ios::app);
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);
fs.seekg(0);
whence:
- ios::beg // start
- ios::cur // current pos
- ios::end // end of file
#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();
}