C++ io流

文章介绍了C++中的基本I/O流类如std::ofstream、basic_ofstream的使用,涉及继承关系、模板参数以及文件读写操作,包括如何使用fstream打开、读取和写入文件,以及成员函数如is_open()和operatorbool()的应用。
摘要由CSDN通过智能技术生成

1. 继承关系

参考
在这里插入图片描述

basic_ostream<CharT, Traits> 输出流
basic_istream<CharT, Traits> 输入流
basic_iostream<CharT, Traits> 输入输出流

上面的三个类是抽象类,所有的实现都继承自它们三个。
Q1: 为什么在实际使用中通常使用的是std::ofstream而不是std::basic_ofstream。
answer: 两者表示相同的意思,只是std::ofstream是别名。

/// Class for @c char output file streams.
typedef basic_ofstream ofstream;

Q2: 模板类有两个模板类型,为什么实际定义中只指定了一个char
answer: 在模板类申明中指定了默认参数。

template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_ofstream;

2. 具体使用

读文件:

#include <fstream>
#include <iostream>
int main(int argc, char const *argv[])
{
    std::string filename = "input.txt";
    // std::basic_ifstream<char, std::char_traits<char>> finstream(filename.c_str());
    std::ifstream fin;
    fin.open(filename, std::ios::in|std::ios::binary);
    if (!fin.is_open()){
        std::cerr << "Error: Failed to open file " << filename << std::endl;        
        return 1;
    }
    std::string str;

    // while (finstream >> str)
    // {
    //     std::cout << str << std::endl;
    // }
    while (std::getline(fin, str))
    {
        std::cout << str << std::endl;
    }
    std::cout << "File opened successfully." << std::endl;
    fin.close();
    return 0;
}

写文件:

#include <iostream>
#include <fstream>

int main(){
    // Open a file for writing
    std::ofstream outfile;
    outfile.open("output.txt", std::ios::out &~std::ios::trunc);
    std::cout <<  std::hex << "std::ios::out "<< static_cast<long>(std::ios::out) << std::endl;
    std::cout <<  std::hex << "std::ios::trunc "<< static_cast<long>(std::ios::trunc) << std::endl;
     std::cout <<  std::hex << "std::ios::out | std::ios::trunc"<< static_cast<long>(std::ios::out | std::ios::trunc) << std::endl;
    // Check if the file was opened successfully
    if (!outfile.is_open())
    {
        std::cout << "File failed to open!" << std::endl;
        return -1;
    }
    // write to the file
    std::string message = "Hello, world!";
    // outfile << message << std::endl;
    // outfile.write(message.c_str(), message.size());
    outfile.put(message.c_str()[0]);
    // close the file
    outfile.close();
    return 0;
}
  1. 支持空构造函数,后面调用open函数
  2. 重写了operator bool()
  3. openmode组合

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

来日可期1314

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

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

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

打赏作者

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

抵扣说明:

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

余额充值