C++文件和流
ofstream 该数据类型表示输出文件流,用于创建文件并向文件写入信息。
ifstream 该数据类型表示输入文件流,用于从文件读取信息。
fstream 该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。
要在 C++ 中进行文件处理,必须在 C++ 源代码文件中包含头文件 和
open函数 打开文件
void open(const char *filename, ios::openmode mode);
打开模式:
ios::app 追加模式。所有写入都追加到文件末尾。
ios::ate 文件打开后定位到文件末尾。
ios::in 打开文件用于读取。
ios::out 打开文件用于写入。
ios::trunc 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。
可以组合使用,如
ofstream outfile// 以写模式打开文件
outfile.open(“file.dat”, ios::out | ios::trunc );以写入模式打开文件,并希望截断文件
ifstream afile;
afile.open(“file.dat”, ios::out | ios::in );打开一个文件用于读写
close函数 关闭文件
fstream outfile;
outfile.open(“afile.dat”);
// 向文件写入用户输入的数据
outfile << data << endl;
outfile.close();
infile >> data;
// 在屏幕上写入数据
cout << data << endl;
C++异常处理
C++ 异常处理涉及到三个关键字:try、catch、throw。
throw: 抛出一个异常的。
catch: 用于捕获异常。
try: try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块
让 catch 块能够处理 try 块抛出的任何类型的异常,则必须在异常声明的括号内使用省略号 …
try
{
// 保护代码
}catch(...)
{
// 能处理任何异常的代码
}
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {//抛出了一个类型为 const char* 的异常
cerr << msg << endl;
}
return 0;
}
定义新的异常
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//其他的错误
}
}
what() 是异常类提供的一个公共方法,它已被所有子异常类重载。这将返回异常产生的原因。