C++ 教程 - 08 文件操作与异常处理

文件操作

  • 需要头文件
    • <iostream>
    • <fstream>
      • 读取文件 ifstream obj; obj.open(const char* filename, std::in)
      • 写入文件ofstream obj; obj.open(const char* filename, std::out)
      • 读、写文件 fstream,包含了ifstream、ofstream两者的功能;
      • open 的其他方式
        • ios::app ,追加写入;
        • ios::in, 读取方式;
        • ios::out,写入方式;
        • ios::trunc,截断(清空内容)
        • ios::in | ios::out,读写方式
  • 读写案例,让用户输入用户名、密码,存入 userInfo.txt 文件中,并从文件中读取,然后打印到控制台;
#include <iostream>
#include <fstream>  // 文件操作
#include <string>
#include <cstring> // C的字符串操作
using namespace std;


int main() {
	
	// 创建写入的文件对象
	ofstream writeFile;
	// 以写的方式 打开文件
	writeFile.open("userInfo.txt", ios::out);  // ios::in | ios::out 读写方式
	
	// 提示信息
	cout << "输入用户名:";
	char* username = new char;
	char* password = new char;
	cin >> username; // 扫描用户输入信息,遇到空格、换行则结束本次扫描,从空格/换行的下一个位置就绪 流提取

	cout << "输入密码:";
	cin >> password;

	//cout << strcat(username, password) << endl;
	
	// 流插入  写入文件
	writeFile << "用户名:" << username << endl; // 写入一行
	writeFile << "密码:" << password << endl;

	// 关闭文件,(程序退出时也会自动关闭文件)
	writeFile.close();


	// 读取文件,并逐行打印
	ifstream readFile;
	readFile.open("userInfo.txt", ios::in); // 以读取方式打开文件

	cout << "\n读取文件:" << endl;
	string uname, passwd;
	getline(readFile, uname); // 从文件中读取一行,存入uname
	getline(readFile, passwd);
	cout << uname << endl;
	cout << passwd << endl;

	return 0;
}

cin 标准输入在流提取时,遇到空格/换行则结束;
cin.getline(char* xx, streamsize count) 提取一行,默认遇到换行结束;
在这里插入图片描述
 

文件对象其他方法

  • (读取)文件对象的相关方法:
    • file.tellg(),获取指针位置,刚打开的文件处于0位置,数据部分指针[0, n],读取结束指针为-1(无法再移动指针);
    • file.seekg(10, ios::beg),从文件的开始位置,向后移动10个字符;
    • file.seekg(-2, ios::cur), 从当前位置,向前移动2个字符;
    • file.seekg(0, ios::end),从末尾位置向前移动0个字符,即定位到末尾位置;
    • file.get() 读取一个字符,返回字符对应的ASCII码值;
    • file.getline(char* cnt, streamsize count),读取一行(count-1个字符),存入字符指针;
    • file.read(char*, numChar),读取num个字符,存入字符数组中;
    • file >> cnt,以流提取方式读取内容,存入cnt;
    • file.is_open() 文件对象是否打开;
    • file.close(),关闭文件
  • (写入)文件对象的方法:
    • writeFile.tellp(),获取文件指针位置;
    • writeFile.seekp(2, ios::cur),移动文件指针位置;
    • writeFile.put(char c) ,写入一个字符;
    • writeFile.write(const char*, streamsize count) 写入一个字符串,count为字符个数;
    • 流插入写入 writeFile << cnt; 将cnt内容 / 值 以流插入方式写入;

 

  • 写入案例
#include <iostream>
#include <fstream>
#include <string>
#include <cstring> // C的字符操作
using namespace std;


int main(){
    // 写入文件
    ofstream writeFile;
    writeFile.open("save.txt", ios::out); // 写入方式,覆盖已有内容

    if (!writeFile.is_open()) {
        cout << "文件打开失败" << endl;
        // 程序退出
        exit(-1);
    }

    const char* cnt = "hello, my name is jack.\n";

    // 写入一行字符串
    writeFile.write(cnt, strlen(cnt)); // strlen 计算字符的个数

    cnt = "second line.\n";
    writeFile.write(cnt, strlen(cnt));

    // 流插入  写入
    int a = 5;
    writeFile << a << endl;
    const char* name = "lucy li";
    writeFile << name << endl;
    string addr = "beijing zhong guan cun";
    writeFile << addr << endl;

    // 关闭文件
    writeFile.close();

    return 0;
}

  • 读取案例,逐行读取上例save.txt文件中的内容;
#include <iostream>
#include <fstream>
#include <string>
#include <cstring> // C的字符操作
using namespace std;


int main(){
    // 写入文件
    ifstream readFile;
    readFile.open("save.txt", ios::in); // 读取方式

    if (!readFile.is_open()) {
        cout << "文件打开失败" << endl;
        // 程序退出
        exit(-1);
    }

    // 流提取 读取
    char* cnt = new char(0); // 创建字符对象,并初始化\0
    char* line = new char(0);
    const char* space = " ";
    while (readFile >> cnt) { // 遇到 空格/换行 结束,直到读取结束,文件位置指针为-1
        cout << cnt << endl;
        strcat(line, cnt);
        strcat(line, space);
        cout << line << endl;
    }

    // std::getline 逐行读取,读取结束文件位置指针为-1
    // getline(readFile, string cnt) 读取一行,存入cnt
    cout << "读取结束的文件指针:" << readFile.tellg() << endl;
   
    // 关闭文件
    readFile.close();


    return 0;
}

在这里插入图片描述

 

异常处理

  • 需要头文件<exception>
  • try { xx } catch (异常类 obj){ } ,可同时使用多个catch代码块捕获多个异常;
  • catch(…){ }, 捕获所有的异常;
  • throw XXX( ) 抛出异常;
  • class MyException: public exception{ } 自定义异常;
  • C++ 提供的标准异常,以继承关系表示;
    在这里插入图片描述
    在这里插入图片描述
#include <iostream>
#include <exception>
using namespace std;


// 定义自己的异常类
class MyException : public exception
{
public:
    string args;
    // 不会继承父类的构造函数
    MyException() {}
    MyException(const string& args) {
        this->args = args;
    }
    virtual ~MyException() {
        cout << "删除对象" << endl;
    }

    //重写 what 虚函数
    const char* what() const throw ()
    {
        // 重写函数体
        return this->args.c_str(); // 转为C字符串,返回值拷贝
    }
};


int main(){
    try
    {
        // 执行的代码,手动抛出异常
        throw MyException("my defined exception");
    }
    catch (const MyException& e)
    {
        cout << "MyException caught" << endl;
        cout << e.what() << std::endl;
    }
    catch (const exception& e)
    {
        //其他的异常
        cout << "其他的异常" << endl;
    }

    return 0;
}

 

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值