2014年01月20日 星期一 17:02
C++标准库中的fstream提供了对于文件的读写操作方法,虽然此模块叫做fstream,但其也提供随机访问所必须的seek操作,功能完备,完全可以替代C语言标准库的stdio模块。
代码示例如下:
#include <iostream>
#include <fstream>
#include <string>
#include <array>
using namespace std;
int main() {
fstream fs;
fs.exceptions(std::fstream::badbit);
fs.open("fstream.cpp",ios_base::in);
if(fs.is_open()) {
array<char,16> buf;
while(!fs.eof()) {
buf.fill(0);
fs.read(buf.data(),15);
cout << buf.data();
}
fs.close();
}
fstream fout("temp.txt",ios_base::out|ios_base::trunc);
fout.exceptions(std::fstream::badbit);
if(fout.is_open()) {
fout << "Hello world" << endl;
auto pos=fout.tellg();
cout << "now pos: " << pos << endl;
fout.seekg(6);
pos=fout.tellg();
cout << "now pos: " << pos << endl;
fout << "WORLD" << endl;
fout << "How are you?" << endl;
array<char,5> str;
str.fill('k');
fout.write(str.data(),str.size());
fout.put('x');
fout.flush();
fout.close();
}
fstream fin("temp.txt",ios_base::in);
if(fin.is_open()) {
fin.seekg(ios_base::beg);
array<char,1024> line;
while(!fin.eof()) {
line.fill(0);
fin.getline(line.data(),1023);
cout << line.data() << endl;
}
fin.close();
}
return 0;
}
参考资料:
Zeuux © 2025
京ICP备05028076号