C++学习,文件输入输出 <fstream>

C++ <fstream> 标准库中文件输入输出操作的类,提供了读写文件方法。fstreamiostream库的一部分,支持文本和二进制文件的读写。fstream类是iostream库中的一个类,它继承自istreamostream类。

<fstream>提供了三个主要的类:ifstream(用于从文件读取数据)、ofstream(用于向文件写入数据)和fstream(同时支持读写操作)。

fstream 的基本语法:

#include <fstream>
int main() {
    std::fstream file; // 创建fstream对象
    file.open("filename", mode); // 打开文件
    // 进行文件操作
    file.close(); // 关闭文件
    return 0;
}

  • std::ios::in:以输入模式打开文件。
  • std::ios::out:以输出模式打开文件。
  • std::ios::app:以追加模式打开文件。
  • std::ios::ate:打开文件并定位到文件末尾。
  • std::ios::trunc:打开文件并截断文件,即清空文件内容。

打开文件:

打开一个文件,这可以通过创建ifstreamofstreamfstream对象,并调用其open方法来实现。也可以在构造这些对象时直接传入文件名来打开文件。

std::fstream file("readwrite.txt", std::ios::in | std::ios::out); // 打开文件以读写

std::fstream file;
file.open("example.txt", std::ios::out); // 以输出模式打开文件

读取文件:

使用ifstream对象,可以从文件中读取数据。常用的读取方法包括>>运算符(用于读取格式化的数据)和getline()函数(用于读取一行文本)。

std::string line;  
while (std::getline(file, line)) {  
    std::cout << line << std::endl; // 输出读取的每一行  
}

写入文件:

file << "Appending this line to the file." << std::endl; // 向文件中写入

关闭文件:

file.close();

示例代码:

#include <fstream>
#include <iostream>

int main() {
    std::fstream file;
    file.open("example.txt", std::ios::app); // 以追加模式打开文件

    if (!file) {
        std::cerr << "Unable to open file!" << std::endl;
        return 1; // 文件打开失败
    }

    file << "Appending this line to the file." << std::endl; // 追加文本
    file.close(); // 关闭文件

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值