C++ IOStream

IOStream

在这里插入图片描述

类流特性

不可赋值和复制

#include <iostream>
#include <fstream>
using namespace std;
void print(fstream fs) //fstream& fs
{
}
int main()
{
    fstream fs1,fs2;
    fs1 = fs2;
    fstream fs3(fs2);
    print(fs3);
  return 0;
}

不同于标准库其他 class 的"值语意",iostream 是"对象语意",即 iostream
是 non-copyable。这是正确的,因为如果 fstream 代表一个文件的话,拷贝一个
fstream 对象意味着什么呢?表示打开了两个文件吗?如果销毁一个 fstream 对象,它会关闭文件句柄,那么另一个 fstream copy 对象会因此受影响吗?

C++ 同时支持"数据抽象"和"面向对象编程",其实主要就是"值语意"与"对象语意
"的区别,标准库里的 complex<> 、pair<>、vector<>、 string 等等都是值语意,
拷贝之后就与原对象脱离关系,就跟拷贝一个 int 一样。而我们自己写的 Employee
class、TcpConnection class 通常是对象语意,拷贝一个 Employee 对象是没有
意义的,一个雇员不会变成两个雇员,他也不会领两份薪水。拷贝 TcpConnection 对
象也没有意义,系统里边只有一个 TCP 连接,拷贝 TcpConnection 对象不会让我们
拥有两个连接。因此如果在 C++ 里做面向对象编程,写的 class 通常应该禁用 copy
constructor 和 assignment operator。

缓冲

下面几种情况会导致刷缓冲
1,程序正常结束,作为 main 函数结束的一部分,将清空所有缓冲区。
2,缓冲区满,则会刷缓冲。
3,endl, flush 也会刷缓冲。

重载了<< >>

#include <iostream>  // 引入标准输入输出流库
#include <fstream>    // 引入文件流库
using namespace std;  // 使用标准命名空间

int main()
{
    // 创建一个 fstream 对象 fs,打开名为 "abc.txt" 的文件,模式为输入、输出和截断(清空文件内容)
    fstream fs("abc.txt", ios::in | ios::out | ios::trunc);

    // 检查文件是否成功打开
    if (!fs)
    {
        // 如果文件打开失败,输出错误信息
        cout << "error" << endl;
    }

    // 向文件中写入数据 "1 2 3"
    fs << 1 << " " << 2 << " " << 3;

    // 将文件指针重新定位到文件开头
    fs.seekg(0, ios::beg);

    // 声明三个整数变量 x, y, z
    int x, y, z;

    // 从文件中读取数据到变量 x, y, z
    fs >> x >> y >> z;

    // 输出读取到的数据
    cout << x << y << z;

    // 程序结束,返回 0 表示成功
    return 0;
}

状态位

大部分情况下 , 我们可能并不关心这些标志状态位 , 比如我们以前用到的 cin/cout。
但是在循环读写中,这些标志位确实大用用途。比如,用于判断文件结束
标志的位。

ios_base.h 中状态位的定义如下:

/// Indicates a loss of integrity in an input or output sequence (such
/// as an irrecoverable read error from a file).
static const iostate badbit = _S_badbit;
/// Indicates that an input operation reached the end of an input sequence.
static const iostate eofbit = _S_eofbit;
/// Indicates that an input operation failed to read the expected
/// characters, or that an output operation failed to generate the
//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

可能只会写BUG

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

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

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

打赏作者

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

抵扣说明:

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

余额充值