一、写入console(文件读取流)
#include <fstream>
#include <string>
#include <iterator>
using namespace std;
int main()
{
// 文件读取数据流
ifstream is('路径', ios::in); // 或者 is.open() 打开文件
// ios::in :向 console 内读入数据
// ios::out :向文件输出数据
// ios::trunc :清空文件内容,再写入
// ios::app : 向文件末尾追加内容
// ios::ate :仅初始时将文件读写指针移动到文末尾,可在任意位置写入数据
// ios::binary :以二进制方式读写文件
1、读取方式
<1>
string a;
is >> a; // 数据流入变量 a
<2>
char *buf;
is.get() // 得到第一个字符的 ascii 码值,读取完后第一个字符被删除
is.get(buf, sizeof(buf), char delim = '\n') // 向 buf 缓冲区写入内容, delim 为结束分割字符
is.getline(buf, sizeof(buf), delim = '\n') // 得到一行数据,写入buf
/*
get() 不提取结束分割字符,在末尾加 '\n', getline() 提取结束分割字符, 但不存入缓存区
*/
<3>
is.read(buf, sizeof(buf)) // 将文本内容写入 buf 缓冲区
2、关闭文件 和 指针偏移
is.close()
is.seekg("偏移位数", ios::beg "文件偏移起始位置") // ios::beg : 移动到文件开头
// ios::cur : 当前位置
// ios::end : 移动到文件末尾
3、迭代器输入流
istream_iterator<int> a(cin); // 读取到非 int 型时截止
istream_iterator<int> b; // 获得流末尾
return 0;
}
二、输出console(文件写入流)
#include <fstream>
#include <iterator>
using namespace std;
int main()
{
ofstream os("路径", ios::app); // 或者 os.open() 打开文件
1、写入方式
<1>
string a = "hello";
os << a;
<2>
char *buf;
os.write(buf, sizeof(buf))
2、指针偏移
os.seekp("偏移数", ios::beg)
3、关闭
os.close()
4、迭代器输出
ofstream_iterator<int> c(cout, ios::app);
/*
*c = 1;
++c; // 指针偏移
*c = 2;
++c;
*c = 3;
输出结果:1 2 3
*/
return 0;
}
三、获取输入输出流状态
.good() : // 返回 true 代表一切正常
.eof() : // 返回 true 表示到达流的末尾
.fail() : // 返回 true 表明 IO操作 失败,但流还可以使用
.bad() : // 返回 true 表明流错误,不可再次使用