C++ 08 标准IO库

特点

  1. IO对象不可复制或赋值
  2. ifstream 由 istream 派生,提供读文件功能。
  3. ofstream 由 ostream 派生,提供写文件功能。
  4. fstream 由 iostream 派生,读写同一个文件。

流状态查询控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;


int main()
{
int ival;
while (cin >> ival, !cin.eof()) // 输入输出绑定 cout关联缓冲区被刷新
{
if (cin.bad()) throw std::runtime_error("IO stream corrupted"); // 流状态检查
if (cin.fail()) {
std::cerr << "bad data , try again";
cin.clear(std::istream::failbit);// 重置输入流
std::istream::iostate old_state = cin.rdstate(); // 流当前整个条件状态
cin.clear(old_state);
continue;
}
cout << "ok," << ival << endl;
cout << "hi" << std::flush; // 刷新 无添加
cout << "hi" << std::ends; // 刷新 添加null
cout << "hi" << std::endl; // 刷新 添加换行
}
return 0;
}

文件流对象使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>
#include <string>
using std::ifstream; using std::ofstream; using std::fstream;
using std::string;using std::cin;using std::cout;using std::endl;

int main()
{
string file1 = "/share/PostLoanData/file.txt";
string file2 = "/share/PostLoanData/file2.txt";
ifstream infile(file1.c_str()); // 打开特点文件
ofstream outfile(file2.c_str());

ifstream infile2;
ofstream outfile2;
infile2.open(file1); // 打开流 再捆绑文件
outfile2.open(file2);
// 判断文件是否打开成功
if (!infile) {
std::cerr << "error: unable to open input file:" << file1 << endl;
return -1;
}
infile.close();
infile.open(file2);// 文件流重新捆绑

infile2.close(); // 清空流
return 0;
}

文件模式

模式 释义
in 打开文件读,ifstream流对象默认模式
out 打开文件写,文件会被清空
app 文件尾追加
ate 打开文件后定位文件尾
trunc 打开文件时清空文件流
binary 二进制模式IO操作
out + app 打开文件写操作,文件尾写入
in + out 打开文件做读写操作,定位文件开头
out + app + trunc 打开文件做读写操作,删除已有数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>
using std::ifstream; using std::ofstream; using std::fstream;
using std::string;using std::cin;using std::cout;using std::endl;

int main()
{
string file1 = "/share/PostLoanData/file.txt";
string file2 = "/share/PostLoanData/file2.txt";
ofstream outfile(file1 , ofstream::app); // 以追加模式打开
outfile << "app add in end" << endl;
outfile.close();
ifstream infile(file1);
string line;
while (infile >> line) {
cout << line ;
}
infile.close();
return 0;
}

字符串流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <sstream>
#include <string>
using std::istringstream; using std::ostringstream;
using std::string; using std::cin; using std::cout; using std::endl;

int main()
{
ostringstream os;
os << "val1: " << 1024 << "\n"
<< "val2: " << 42 << "\n";
istringstream is(os.str());
string dump;
int val1, val2;
is >> dump >> val1 >> dump >> val2;
cout << val1 << "," << val2 << endl;
return 0;
}

推荐文章