Skip to content
Word Count: 739 | Expected Read Time: 3 min

ECE244笔记-3-文件IO·错误处理与字符串流

C++ File IO

C++中的文件输入输出流分别存在于ifstream 和 ofstream 类中, 他们存在于 <fstream>头文件中.

写入文件

法1: 把文件名作为参数传给构造器

1
ofstream outFile("File.txt");

法2: 先创建一个对象, 然后使用open方法

1
2
ofstream outFile;
outFile.open("File.txt");

注意: 此处的文件名亦可使用绝对路径或者相对路径代替, 如果文件不存在则会在尝试打开时被创建

最后, 使用类似cout的语法将内容输出至文件

1
outFile << "content" << endl;

如果希望追加写入, 可以通过传入 ios::app来指定写入模式

1
2
3
ofstream outFile;
outFile.open("File.txt", ios::app);
// or just ostream outFile("File.txt", ios::app);

最后, 在完成写入后, 要关闭文件流, 否则写入的内容可能依然处于缓冲区中, 没有被正确写入文件

1
outFile.close()

缓冲区

文件写入的速度可能很慢, 但是缓冲区的存在可以允许程序一次性将一大块数据写入缓冲区, 从而提升性能

在以下几种情况下, 缓冲区内的内容会被flush到文件中

  1. 输出中存在 \n或者endl
  2. 显式调用 outFile.flush()
  3. 关闭输出流

读取文件

相似地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <fstream>
using namespace std;

int main(void){
ifstream inFile;
inFile.open("File.txt");
// or just: ifstream inFile("File.txt");

int num1, num2;
inFile >> num1 >> num2;
cout << "num1: " << num1 << ", num2: " << num2 << endl;
inFile.close();
return 0;
}

IO 错误处理

获取错误状态

当一个IO流错误发生错误的时候, 其 failbit会变为true, 可以通过以下代码获取 failbit的值

1
cin.fail();

清除或忽略错误

可以使用 .clean()方法将failbit 显式设置为false

或者可以使用 .ignore(<int n>, <char c>);方法来忽略错误. 其参数表示

  • n: 忽略至多n个字符
  • c: 忽略直到出现c字符

两个条件哪个先满足, 就结束忽略.

例如, 可以通过如下代码处理文件不存在的问题

1
2
3
4
5
ifstream inFile("File.txt");
if (inFile.fail()) {
cerr << "Error opening file" << endl;
return 1; // exit the program with an error code
}

EOF

使用.eof()方法判断文件是否达到末尾, 以下是一个示例

1
2
3
4
5
6
7
8
9
10
11
ifstream inFile("File.txt");
if (inFile.fail()) {
cerr << "Error opening file" << endl;
return 1; // exit the program with an error code
}
int num;
while (!inFile.eof()) {
// read data from the file
inFile >> num;
cout << num << endl;
}

String Streams

String Streams相关实现被封装在 sstream头文件中, 它允许我们像标准输入输出流一样从字符串中读取/写入内容. 其在需要从一行文本中解析多个输入的时候非常有用, 因为它可以有效避免输入失败的风险.

可以通过以下代码实例化一个sstream对象

1
2
3
stringstream ss(line);
//int id;
//ss >> id;

可以通过.str()获取该String Stream的原始字符串

About this Post

This post is written by Jinyuan Zhou, licensed under CC BY-NC 4.0.

#C/C++ #ECE244