C++ 流(stream)总结
框架:
C++中流的概念
C++流涉及以下概念:
标准I/O流:内存与标准输入输出设备之间信息的传递;
文件I/O流:内存与外部文件之间信息的传递;
字符串I/O流:内存变量与表示字符串流的字符数组之间信息的传递
STL中定义的流类:
流类分类 | 流类名称 | 流 类 作 用 |
---|---|---|
流基类 | ios | 所有流类的父类,保存流的状态并处理错误 |
输入流类 | istream | 输入流基类,将流缓冲区中的数据作格式化和非格式化之间的转换并输入 |
… | ifstream | 文件输入流类 |
… | istrstream | 串输入流类, 基于C类型字符串char*编写 |
输出流类 | ostream | 输出流基类,将流缓冲区中的数据作格式化和非格式化之间的转换。并输出 |
… | ofstream | 文件输出流类 |
… | ostrstream | 串输入流类, 基于C类型字符串char*编写 |
输入/输出流类 | iostream | 多目的输入/输出流类的基类 |
… | fstream | 文件流输入/输出类 |
… | strstream | 串流输入/输出类, 基于C类型字符串char*编写 |
注,对于串流,提供了两套类,一个基于C类型字符串char *编写(定义于头文件strstream),一个基于std::string编写(定义于sstream), 后者是C++标准委员会推荐使用的。
文件流
打开方式
以上打开方式, 可以使用位操作 | 组合起来
想对文件进行写入操作,当文件已经存在时,你希望对该文件进行截断操作
fstream stream;
stream.open("demo.txt", ios::out | ios::trunc);
想对文件进行读取操作,而且想在文件尾部读取
fstrem inFile;
inFile.open("demo.txt", ios::in | ios::ate);
文件流二进制读写
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ifstream infile;
ofstream outfile;
std::vector<char> buffer;
infile.open("E:/Desktop/girl.jpg", std::ifstream::binary);
//获取文件长度
infile.seekg(0, std::ifstream::end);
long size = infile.tellg();
infile.seekg(0);
//写入buffer
buffer.resize(size);
infile.read(&buffer[0], size);
//写入二进制文件
outfile.open("E:/Desktop/girl.bin", std::ofstream::binary);
outfile.write(&buffer[0], buffer.size());
infile.close();
outfile.close();
}
使用流操作算子 setiosflags
参考: link
例如下面的三条语句:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n = 141;
//1) 分别以十六进制、十进制、八进制先后输出 n
cout << "1)" << hex << n << " " << dec << n << " " << oct << n << endl;
double x = 1234567.89, y = 12.34567;
//2)保留5位有效数字
cout << "2)" << setprecision(5) << x << " " << y << " " << endl;
//3)保留小数点后面5位
cout << "3)" << fixed << setprecision(5) << x << " " << y << endl;
//4)科学计数法输出,且保留小数点后面5位
cout << "4)" << scientific << setprecision(5) << x << " " << y << endl;
//5)非负数显示正号,输出宽度为12字符,宽度不足则用 * 填补
cout << "5)" << showpos << fixed << setw(12) << setfill('*') << 12.1 << endl;
//6)非负数不显示正号,输出宽度为12字符,宽度不足则右边用填充字符填充
cout << "6)" << noshowpos << setw(12) << left << 12.1 << endl;
//7)输出宽度为 12 字符,宽度不足则左边用填充字符填充
cout << "7)" << setw(12) << right << 12.1 << endl;
//8)宽度不足时,负号和数值分列左右,中间用填充字符填充
cout << "8)" << setw(12) << internal << -12.1 << endl;
cout << "9)" << 12.1 << endl;
return 0;
}
输出结果是:
1)8d 141 215
2)1.2346e+06 12.346
3)1234567.89000 12.34567
4)1.23457e+06 1.23457e+01
5)***+12.10000
6)12.10000****
7)****12.10000
8)-***12.10000
9)12.10000
重定向 freopen
#include <iostream>
using namespace std;
int main()
{
int x,y;
cin >> x >> y;
freopen("test.txt", "w", stdout); //将标准输出重定向到 test.txt文件
if( y == 0 ) //除数为0则输出错误信息
cerr << "error." << endl;
else
cout << x /y ;
return 0;
}