兜兜零元 发表于 2024-11-8 01:38:15

C++ IOStream


[*]IOStream

[*]类流特性

[*]不可赋值和复制
[*]缓冲
[*]重载了<< >>


[*]状态位

[*]示例

[*]状态位利用函数
[*]cout
[*]cin

[*]get
[*]get(s,n)/get(s,n,d):
[*]getline

[*]other
[*]if(!fs)/while(cin)

[*]operator void*()与 operator!()
[*]代码示例

[*]File Stream

[*]open 函数

[*]文件打开方式


[*]文件读写

[*]读写接口

[*]一次读一个字符
[*]一次读一行
[*]读写二进制


[*]文件指针相关的函数
IOStream

https://i-blog.csdnimg.cn/direct/6fe4398e2c3f427b88a445aa12c9f6ee.png
类流特性

不可赋值和复制

#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
/// desired characters.
static const iostate failbit = _S_failbit;
/// Indicates all is well.
static const iostate goodbit = _S_goodbit;
在C++标准库中,ios_base.h头文件定义了输入输出流的基础类ios_base,以及与之相关的各种枚举和常量。
其中,状态位(state flags)用于表示流的状态。
这些状态位可以通过ios_base类的成员函数进行设置和查询。

以下是一些常用的状态位:

goodbit:表示流处于正常状态,没有错误。
badbit:表示流发生了致命错误,可能导致数据丢失。
failbit:表示流发生了可恢复的错误,通常是由于格式错误或无效输入。
eofbit:表示流已经到达文件末尾。

这些状态位可以通过ios_base类的以下成员函数进行操作:

rdstate():返回当前的状态位。
setstate(iostate state):设置指定的状态位。
clear(iostate state = goodbit):清除当前的状态位,并设置为指定的状态位。
示例

在这个例子中,我们打开一个文件并检查其状态。
如果文件无法打开,步伐会输堕落误信息并退出。
然后,我们尝试从文件中读取数据,
并检查读取利用后的状态位,以确定是否乐成读取数据或是否到达文件末端。
#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.txt");
    if (!file) {
      std::cerr << "无法打开文件" << std::endl;
      return 1;
    }

    // 检查流的状态
    if (file.rdstate() & std::ios_base::failbit) {
      std::cerr << "流发生了可恢复的错误" << std::endl;
    }

    // 读取文件内容
    int data;
    file >> data;

    // 检查读取操作后的状态
    if (file.rdstate() & std::ios_base::eofbit) {
      std::cout << "已到达文件末尾" << std::endl;
    }
    if (file.rdstate() & std::ios_base::failbit) {
      std::cerr << "读取操作失败" << std::endl;
    }

    file.close();
    return 0;
}

状态位利用函数

函数功能eof()如果读文件到达文件末端,返回 true。fail()除了与 bad() 同样的情况下会返回 true 以外,加上格式错误时也返回 true , 例如当想要读入一个整数,而获得了一个字母的时间。或是碰到 eof。bad()如果在读写过程中堕落,返回 true 。例如:当我们要对一个不是打开为写状态的文件举行写入时,大概我们要写入的设备没有剩余空间的时间。clear()标识位一旦被置位,这些标记将不会被改变,要想重置以上成员函数所检查的状态标记,你可以使用成员函数 clear(),没有参数。好比:通过函数移动文件指针,并不会使 eofbit 自动重置。good()这是最通用的:如果调用以上任何一个函数返回 true 的话,此函数返回 false 。 在这段代码中,主要使用了以下几个与输入流状态相关的函数:

cin.eof():

功能:检查是否到达文件末尾(EOF)。
返回值:如果到达文件末尾,返回true;否则返回false。
使用场景:通常在读取文件时使用,用于判断是否已经读取到文件的末尾。

cin.fail():

功能:检查是否发生格式错误。例如,尝试将非数字字符读取为整数时会触发格式错误。
返回值:如果发生格式错误,返回true;否则返回false。
使用场景:用于检测输入操作是否因为格式不匹配而失败。

cin.bad():

功能:检查是否发生致命错误。例如,流被破坏或硬件故障等。
返回值:如果发生致命错误,返回true;否则返回false。
使用场景:用于检测流是否处于不可恢复的错误状态。

cin.good():

功能:检查流是否处于良好状态,即没有发生任何错误。
返回值:如果流处于良好状态,返回true;否则返回false。
使用场景:用于检测流是否可以正常使用。

cin.clear():

功能:清除流的错误状态标志。调用此函数后,流的failbit和badbit会被清除,流的状态会被重置为良好状态。
参数:可以传递一个参数来指定要清除的错误标志,默认情况下会清除所有错误标志。
使用场景:在检测到输入错误后,通常需要调用此函数来清除错误状态,以便继续使用流进行后续的输入操作。

通过这些函数,程序可以有效地检测和处理输入流中的错误,确保输入操作的可靠性和程序的健壮性。
在实际应用中,这些函数常用于输入验证和错误处理,以提高程序的容错能力。

#include <iostream>
using namespace std;

int main()
{
    int val;

    // 输出在错误输入操作之前的流状态
    cout << "Before a bad input operation:"
         << "\n cin.eof() : " << cin.eof()// 检查是否到达文件末尾
         << "\n cin.fail(): " << cin.fail() // 检查是否发生格式错误
         << "\n cin.bad() : " << cin.bad()// 检查是否发生致命错误
         << "\n cin.good(): " << cin.good() // 检查流是否处于良好状态
         << endl;

    // 尝试从标准输入读取一个整数,可以通过输入非数字字符(如'a')或模拟文件结束(如在Unix系统上按Ctrl+D,在Windows系统上按Ctrl+Z)来触发错误
    cin >> val;

    // 输出在错误输入操作之后的流状态
    cout << "After a bad input operation:"
         << "\n cin.eof() : " << cin.eof()// 检查是否到达文件末尾
         << "\n cin.fail(): " << cin.fail() // 检查是否发生格式错误
         << "\n cin.bad() : " << cin.bad()// 检查是否发生致命错误
         << "\n cin.good(): " << cin.good() // 检查流是否处于良好状态
         << endl;

    // 清除流的错误状态标志
    cin.clear();

    // 输出清除错误状态标志后的流状态
    cout << "\n cin.eof() : " << cin.eof()// 检查是否到达文件末尾
         << "\n cin.fail(): " << cin.fail() // 检查是否发生格式错误
         << "\n cin.bad() : " << cin.bad()// 检查是否发生致命错误
         << "\n cin.good(): " << cin.good() // 检查流是否处于良好状态
         << endl;

    return 0;
}


cout

格式输出:
https://i-blog.csdnimg.cn/direct/78538efc502142d69108159ee65a6dcb.png
成员函数:
函数功能ostream& put( char )输出一个字符ostream& write( const char* s, streamsize n )输出一个字符串ostream& operator<<(T v)输出一个值 cin

get

函数声明
int get();
istream& get (char& c);
istream& get (char* s, streamsize n);          //终止符为'\n'
istream& get (char* s, streamsize n, char delim);

#include <iostream>
using namespace std;
int main()
{
    char ch;
    while((ch = cin.get())!=EOF)
    {
      cout<<ch<<endl;
    }
    while(cin.get(ch))
    {
      cout<<ch<<endl;
    }
    return 0;
}
get(s,n)/get(s,n,d):

#include <iostream>
using namespace std;
int main()
{
    char ch;
    char buf;
    while(cin.get(buf,10))
    {
      cout<<buf<<endl;
    }
    cout<< "\n cin.eof() : " <<cin.eof()
      << "\n cin.fail(): " <<cin.fail()
      << "\n cin.bad() : " <<cin.bad()
      << "\n cin.good(): " <<cin.good()<<endl;
    return 0;
}
输出:
12345678901234567890
123456789
012345678
90

cin.eof() : 0
cin.fail(): 1
cin.bad() : 0
cin.good(): 0

#include <iostream>
using namespace std;
int main()
{
    char ch;
    char buf;
    while(cin.get(buf,10,'S'))
    {
      cout<<buf<<endl;
    }
    cout<< "\n cin.eof() : " <<cin.eof()
      << "\n cin.fail(): " <<cin.fail()
      << "\n cin.bad() : " <<cin.bad()
      << "\n cin.good(): " <<cin.good()<<endl;
    return 0;
}
输出:
cvdScjkvds
cvd

cin.eof() : 0
cin.fail(): 1
cin.bad() : 0
cin.good(): 0
getline

函数声明
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

在读取 n-1 个字符前,遇到标志位,则会读到标志位前的字符。然后越过标志位
继续读取。
若在读到 n-1 个字符前没有遇到标志位,则会退出。
#include <iostream>
using namespace std;
int main()
{
    char buf;
    while(cin.getline(buf,10))
    {
      cout<<buf<<endl;
    }
    cout<< "\ncin.eof() : " <<cin.eof()
      << "\ncin.fail(): " <<cin.fail()
      << "\ncin.bad() : " <<cin.bad()
      << "\ncin.good(): " <<cin.good()<<endl;
    return 0;
}
输出
1234567890

cin.eof() : 0
cin.fail(): 1
cin.bad() : 0
cin.good(): 0

输出
123456789
123456789

ad fd gd
ad fd gd
#include <iostream>
using namespace std;
int main()
{
    char buf;
    while(cin.getline(buf,10,'x'))
    {
      cout<<buf<<endl;
    }
    cout<< "\ncin.eof() : " <<cin.eof()
      << "\ncin.fail(): " <<cin.fail()
      << "\ncin.bad() : " <<cin.bad()
      << "\ncin.good(): " <<cin.good()<<endl;
    return 0;
}
输出
12x22x23x
12
22
23
other

函数声明

istream& ignore (streamsize n = 1, int delim = EOF);
跳过流中的 n 个字符,或遇到终止字符为止(包含),默认参数忽略一个字符。

int peek();
窥视当前指针,文件指针未发生移动

istream& putback (char c);
回推插入当前指针位置
#include <iostream>
using namespace std;

int main()
{
    char ch;

    // 使用cin.get读取输入,最多读取19个字符,直到遇到'/'为止
    // 例如输入 "i like c/ i like C++ also/",将读取 "i like c"
    cin.get(ch, 20, '/');
    cout << "the first part is :" << ch << endl;

    // 忽略接下来的10个字符或直到遇到字符'i'为止
    cin.ignore(10, 'i');

    // 将字符'i'放回输入流的最前面
    cin.putback('i');

    // 查看输入流中的下一个字符,但不移除它
    // 由于之前putback('i'),所以peek将是'i'
    char peek = cin.peek();
    cout << "peek is :" << peek << endl;

    // 再次使用cin.get读取输入,最多读取19个字符,直到遇到'/'为止
    cin.get(ch, 20, '/');
    cout << "this second part is:" << ch << endl;

    return 0;
}

输出
i like c/ i like C++ also/
the first part is :i like c
peek is :i
this second part is:i like C++ also
if(!fs)/while(cin)

在判断文件打开乐成与否或是一连从流中读取数据时,就要用到对流对像的利用,
好比 if(!fs)和 while(cin>>val),
我们都知道 cin 是一个流对象,
而>>运算符返回左边的流对象,也就是说 cin>>val 返回 cin,
于是 while(cin>>val)就变成了while(cin),问题就变成了一个流对象在判断语句中的合法性。
不管是 while(cin)还是 if(!fs),都是合法的,为什么呢?
我们自己定义一个类,然后定义该类的对象,然后使用 if 语句来判断它是不合法
的。
这说明,流对象具有某种转换函数,可以将一个流对象转换成判断语句可以识别的范例。
operator void*()与 operator!()

打开 iostream.h 文件,找到 cin 的定义,发现是来自于 istream.h,其中的模
板类 basic_istream 继承自 basic_ios,打开 basic_ios 的定义,发现它有两个重载
函数。
operator void *() const 和 operator!() const。这两个函数使得流对象
可作为判断语句的内容。
operator void*() const //转化函数 A 类对象-> void *对象
{
return this->fail() ? 0 : const_cast<basic_ios*>(this);
}
bool operator!() const //运算符重载函数 对象调用 operator!()
{
return this->fail();
}
常见策略
while(cin)===> while(!cin.fail())   //while the stream is OK
if(!cin)    ===> if(cin.fail())      //if the stream is NOT OK
代码示例


#if 1
#include <iostream>
using namespace std;

class A
{
public:
    A() {}// 构造函数
    ~A() {} // 析构函数

    // 类型转换运算符,将对象转换为void*类型
    operator void* () const
    {
      cout << "operator void* () cast to void*; " << endl;
      return (void *)this;// 返回当前对象的指针
    }

    // 重载逻辑非运算符
    bool operator!() const
    {
      cout << "bool operator!() return bool; " << endl;
      return true;// 返回true
    }
};

int main()
{
    A a;// 创建对象a

    // 使用对象a作为while循环的条件
    // 由于a可以隐式转换为void*类型,且void*类型的非零值被视为true
    while (a) {
      cout << "while" << endl;
      break;// 跳出循环
    }

    // 使用对象a作为if语句的条件
    // 由于a可以隐式转换为void*类型,且void*类型的非零值被视为true
    if (a) cout << "first" << endl;

    // 使用逻辑非运算符!a作为if语句的条件
    // 由于重载了!运算符,返回true
    if (!a) cout << "second" << endl;

    return 0;
}

# endif
输出
operator void* () cast to void*;
while
operator void* () cast to void*;
first
bool operator!() return bool;
second
File Stream

对文件的利用是由文件流类完成的。文件流类在流与文件间建立连接。由于文件流
分为三种:文件输入流、文件输出流、文件输入/输出流,所以相应的必须将文件流说
明为 ifstream、ofstream 和 fstream 类的对象,然后利用文件流的对象对文件举行利用
   对文件的利用过程可按照以下四步举行:即定义文件流类的对象、打开文件、对文
件举行读写利用、关闭文件,下面分别举行介绍。
流对象的定义

//流类 流对象;
ifstream ifile; //定义一个文件输入流对象
ofstream ofile; //定义一个文件输出流对象
fstream iofile; //定义一个文件输出/输入流对象
open 函数

定义了文件流对象后,就可以利用其成员函数 open()打开需要利用的文件,该
成员函数的函数原型为:
void open(const unsigned char *filename,int mode,int access=filebuf:openprot);

其中:filename 是一个字符型指针,指定了要打开的文件名;
mode 指定了文件的打开方式,其值如下表所示;
access 指定了文件的系统属性,取默认即可
文件打开方式

打开方式值寄义ios::in0x01以输入(读)方式打开文件,若文件不存在则报错。ios::out0x02以输出(写)方式打开文件, 若文件不存则创建。ios::ate0x04打开文件时指针指向文件尾ios::app0x08打开一个文件使新的内容始终添加在文件的末端,若文件不存在,则创建。ios::trunc0x10若文件存在,则截断文件ios::binary0x80以二进制方式打开文件,缺省时以文本方式打开文件。ios::nocreate0x20若文件不存在,则打开失败,而不是创建文件。ios::noreplace0x40若文件存在,则打开失败,而不是覆盖文件。 几点说明:

a.在实际使用过程中,可以根据需要将以上打开文件的方式用"|"组合起来。如:
ios::in|ios::out
表示以读/写方式打开文件

ios::in|ios:: binary
表示以二进制读方式打开文件

ios::out|ios:: binary
表示以二进制写方式打开文件

ios::in|ios::out|ios::binary 表示以二进制读/写方式打开文件



b.如果未指明以二进制方式打开文件,则默认是以文本方式打开文件。

c.构造函数打开文件

对于 ifstream 流, mode 参数的默认值为 ios::in,
对于 ofstream 流,mode 的默 认值为 ios::out|ios::trunc,
对于 fstream 流, mode 的默认值为 ios::int|ios::out|ios::app

d.ios::int|ios::out 是是命名空间的 ios 中一堆枚举
文件读写

读写接口

https://i-blog.csdnimg.cn/direct/5618e9fd58254024a4e9ec1f05b0d50c.png
一次读一个字符

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    // 创建一个 fstream 对象 fs
    fstream fs;

    // 以读写模式打开文件 "test.txt",如果文件存在则截断文件
    fs.open("test.txt", ios::in | ios::out | ios::trunc);

    // 检查文件是否成功打开
    if (!fs)
    {
      cout << "open error" << endl;
      return -1; // 如果打开失败,返回 -1
    }

    // 向文件中写入从 'a' 到 'z' 的字符
    for (char c = 'a'; c <= 'z'; c++)
    {
      fs.put(c); // 将字符 c 写入文件
    }

    // 将文件指针移动到文件开头
    fs.seekp(0, ios::beg);

    // 从文件中读取字符并输出到控制台
    char ch;
    while (fs.get(ch)) // 从文件中读取一个字符并存储到 ch 中
    {
      cout << ch << endl; // 输出字符 ch 并换行
    }

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

    // 程序正常结束,返回 0
    return 0;
}

可以用<<和>>
for(char c='a';c<='z';c++){
      fs<<c;
    }
    fs.seekp(0,ios::beg);

    char ch;
    while (fs>>ch){
      cout<<ch<<endl;
    }
一次读一行


#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream fs;
    fs.open("test.txt",ios::in|ios::out|ios::trunc);
    if(!fs)
    {
      cout<<"open error"<<endl;
      return -1;
    }


    //按行写入
    fs<<"hello world1"<<endl;
    fs<<"hello world2"<<endl;
    fs<<"hello world3"<<endl;

    fs.seekp(0,ios::beg);


    char buf;
    while (fs>>buf){ //读取一行 以空格换行符为分隔
      cout<<buf<<endl;
    }
   

    //getline读到换行符为止,但是会丢弃换行符,所以要补上换行符
    while (fs.getline(buf,100,'\n')){//'\n'参数不加也是可以的,默认就是换行符
            cout<<buf<<endl;//补上换行符
    }

   
    fs.close();
    return 0;
}

读写二进制

读写接口:
ostream & write(const char*buf, int len);
istream & read(char * buff, int len);
#include <iostream>
#include <fstream>
using namespace std;

// 定义学生结构体
struct Student
{
    char name; // 学生姓名
    int num;      // 学生学号
    int age;      // 学生年龄
    char sex;       // 学生性别
};

int main() {
    fstream fs; // 定义文件流对象

    // 打开文件,模式为读写和截断(如果文件存在,清空文件内容)
    fs.open("test.txt", ios::in | ios::out | ios::trunc);

    // 检查文件是否成功打开
    if (!fs) {
      cout << "open error" << endl;
      return -1; // 打开失败,返回错误码
    }

    // 定义并初始化学生数组
    Student s = {
            {"li",   1001, 18, 'f'},
            {"liu",1002, 19, 'm'},
            {"Wang", 1004, 17, 'f'}
    };

    // 将学生数组以二进制形式写入文件
    fs.write((char*)&s, sizeof(s));

    // 将文件指针移动到文件开头
    fs.seekp(0, ios::beg);

    Student s1; // 定义一个学生结构体变量用于读取数据

    // 从文件中读取数据,直到文件结束
    while (fs.read((char*)&s1, sizeof(s1))){
      // 输出读取到的学生信息
      cout << s1.name << " " << s1.num << " " << s1.age << " " << s1.sex << endl;
    }

    fs.close(); // 关闭文件
    return 0; // 程序正常结束
}

输出
li 1001 18 f
liu 1002 19 m
Wang 1004 17 f
文件指针相关的函数

https://i-blog.csdnimg.cn/direct/b77edca1c89647dab1094cf992da2506.png
   g 代表 get 的意思用于输入的函数。p 代表 put 的意思,用于输出函数。如果既是
可输入又是可输出的文件,则任意使用。
https://i-blog.csdnimg.cn/direct/9b5679c55b6a4b17b35d68fd0fa98a4c.png
代码示例:

infile.seekg(100);//输入文件中的指针向前移到 100 个字节的位置
infile.seekg(-50,ios::cur); //输入文件中的指针从当前位置后移 50 个字节
outfile.seekp(-75,iso::end); //输出文件中指针从文件尾后移 75 个字节

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: C++ IOStream