一、C++中流的架构
二、iostream
iostream对istream对象cin和ostream对象cout进行了封装
三、fstream
标准流程
- 建立和文件的连接
- 读或写文件
- 关闭连接
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//写文件
ofstream outfile;
outfile.open("./test.txt");
if (outfile.is_open()) { //判断文件是否成功打开
outfile << "This is a test text";
outfile.close();
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//读文件
string s;
ifstream infile;
infile.open("./test.txt");
if (infile.is_open()) {
while (true) {
if (!infile.eof()) { //判断文件是否读到结尾
infile >> s; //读的时候遇到空格、回车、table会截断
cout << s << endl;
} else {
break;
}
}
infile.close();
}
return 0;
}
四、文件读写方式
标志 | 含义 |
---|---|
ios::in | 为输入(读)而打开文件 |
ios::out | 为输出(写)而打开文件 |
ios::app | 写文件的时候直接接续文件末尾进行 ,(只能用于写文件,不能和ios::in配合使用) |
ios::ate | 将文件指针移到末尾,(和ios::in配合,定位到文件末尾,和ios::out配合,会清空原文件) |
ios::trunc | 写文件的时候会清除之前所有的内容 ) |
五、文件流的定位
函数 | 含义 |
---|---|
ifstream.tellg() | 从读取的文件中获得当前的读入位置 |
ofstream.tellp() | 从写入的文件中获得当前的写入位置 |
ifstream.seekg(2,ios::beg) | 在读取的文件中设置读入位置 |
ofstream.seekp(2,ios::beg) | 在写入的文件中设置当前的写入位置 |
指针标记 | 含义 |
---|---|
ios::beg | 文件的开始 |
ios::cur | 当前的读写位置 |
ios::end | 文件的末尾 |
六、sstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
stringstream s;
s << "abc" << 123 << 456.78f; //可以将非字符串类型放入流程转换成字符串
cout << s.str() << endl; //将流转换成字符串输出
return 0;
}