//读二进制文件
使用文件流对象的read方法.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ifstream infile;
infile.open("user.dat", ios::in | ios::binary);
while (1) {
infile >> name;
if (infile.eof()) { //判断文件是否结束
break;
}
cout << name << "t";
// 跳过中间的制表符
char tmp;
infile.read(&tmp, sizeof(tmp));
//infile >> age; //从文本文件中读取整数, 使用这个方式
infile.read((char*)&age, sizeof(age));
cout << age << endl; //文本文件写入
}
// 关闭打开的文件
infile.close();
system("pause");
return 0;
}
对文件流按格式读写取数据
使用stringstream
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile;
outfile.open("user.txt", ios::out | ios::trunc);
while (1) {
cout << "请输入姓名: [ctrl+z退出] ";
cin >> name;
if (cin.eof()) { //判断文件是否结束
break;
}
cout << "请输入年龄: ";
cin >> age;
stringstream s;
s << "name:" << name << "ttage:" << age << endl;
outfile << s.str();
}
// 关闭打开的文件
outfile.close();
system("pause");
return 0;
}
按指定格式读文件
没有优雅的C++解决方案, 使用C语言的sscanf
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <Windows.h>
using namespace std;
int main(void)
{
char name[32];
int age;
string line;
ifstream infile;
infile.open("user.txt");
while (1) {
getline(infile, line);
if (infile.eof()) { //判断文件是否结束
break;
}
sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name, sizeof(name),&age);
cout << "姓名:" << name << "tt年龄:" << age << endl;
}
infile.close();
system("pause");
return 0;
}
文件流的状态检查
s.is_open( )
文件流是否打开成功,
s.eof( ) 流s是否结束
s.fail( )
流s的failbit或者badbit被置位时, 返回true
failbit: 出现非致命错误,可挽回, 一般是软件错误
badbit置位, 出现致命错误, 一般是硬件错误或系统底层错误, 不可挽回
s.bad( )
流s的badbit置位时, 返回true
s.good( )
流s处于有效状态时, 返回true
s.clear( )
流s的所有状态都被复位
文件流的定位
seekg( off_type offset, //偏移量
ios::seekdir origin ); //起始位置
作用:设置输入流的位置
参数1: 偏移量
参数2: 相对位置
beg 相对于开始位置
cur 相对于当前位置
end相对于结束位置










