C++ fstream 处理文件读写示例

本文介绍了C++中处理文件的三种方式,重点讲解了ifstream用于读取文本文件逐行数据和ofstream用于写入文件的示例,展示了如何使用这两个类进行文件操作。
摘要由CSDN通过智能技术生成

一、读写文件方式

使用C++标准库的类,有三种方式可以处理文件读写,包括文本文件和二进制文件。cplusplus-fstream官网

方式描述
fstream输入输出文件,可以同时进行读写
ifstream输入文件,也就是读文件
ofstream输出文件,也就是写文件

二、文本文件示例

1、ifstream

当前场景每行每行读取,当然也可以read自定义读取

#include <fstream>
void readFromFile(const std::string& dictPath)
{
    std::ifstream in(dictPath);
    if (!in.is_open())
    {
        printf("dictPath is invalid!!\n");
        return;
    }
 
    std::string line;
    while (std::getline(in, line))
    {
        if (!line.empty()) //防止末尾有空行,越界
        {
            // 假设每行数据为 `675C杜`
            std::string str1 = line.substr(0, 4); // 提取前四个字符  
            std::string str2 = line.substr(5);  // 提取后面的文字
        }
    }
    in.close();
}
2、ofstream
bool makeFile(const std::string& dictPath)
{
    std::ofstream outputFile(dictPath);

    if (outputFile.is_open()) {
        std::string str1 = "hello";
        std::string str2 = "world";
			
        outputFile << str1 << "\t" << str2 << "\n";  // `\t`代表Tab制表符
        outputFile.close();
    }
    else {
        return false;
    }
    return true;
}
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值