c++输入文件流ifstream用法详解

article/2025/10/7 14:57:04

目录

文章目录

      • 输入流的继承关系:
      • 成员函数
      • Public member functions
        • 1, (constructor)
        • 2,ifstream::open
        • 3,ifstream:: is_open
        • 4,ifstream:: close
        • 5,ifstream:: rdbuf
        • 6,ifstream:: operator =
      • Public member functions inherited from istream
        • 7,std::istream::operator>>
        • 8,istream::gcount
        • 9,istream::get
        • 10,istream::getline
        • 11,istream::ignore
        • 12,istream::peek
        • 13,istream::read
        • 14,istream::putback
        • 15,istream::unget
        • 16,istream::tellg
        • 17,istream::seekg
      • Public member functions inherited from ios
        • 18,ios::good
        • 19,ios::operator!
        • 20,ios::operator bool
        • 21,ios::rdstate

输入流的继承关系:

ios_base <- ios <- istream <- ifstream

这里写图片描述

C++ 使用标准库类来处理面向流的输入和输出:

  • iostream 处理控制台 IO
  • fstream 处理命名文件 IO
  • stringstream 完成内存 string 的IO

每个IO 对象都维护一组条件状态 flags (eofbit, failbit and badbit),用来指出此对象上是否可以进行 IO 操作。如果遇到错误—例如输入流遇到了文件末尾,则对象的状态变为是失效,所有的后续输入操作都不能执行,直到错误纠正。


头文件 <fstream>包含的多个文件流类,这里列出常用的4个:

  • ifstream Input file stream class (class )链接
  • ofstream Output file stream (class )链接
  • fstream Input/output file stream class (class )链接
  • filebuf File stream buffer (class )链接

成员函数

Public member functions

1, (constructor)

第一种不绑定文件,后续用open() 绑定。
第二种绑定文件 filename ,读取模式默认参数为 ios_base::in可以省略。

default (1)	ifstream();
initialization (2)	
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);

2,ifstream::open

打开文件filename,模式默认 ios_base::in

void open (const   char* filename,  ios_base::openmode mode = ios_base::in);
void open (const string& filename,  ios_base::openmode mode = ios_base::in);

函数参数:

  • filename 要打开文件的文件名
  • mode 打开文件的方式
member constantstands foraccess
ininput File读的方式打开文件
outoutput写的方式打开文件
binarybinary二进制方式打开
ateat end打开的时候定位到文件末尾
appappend所有操作都定位到文件末尾
trunctruncate丢弃打开前文件存在的内容

3,ifstream:: is_open

bool is_open() const;

文件流对象与文件绑定,返回 true ,否则 false 。

4,ifstream:: close

void close();   //关闭文件流

5,ifstream:: rdbuf

filebuf* rdbuf() const;    

返回一个 filebuf 对象指针,(The pointer to the internal filebuf object.

6,ifstream:: operator =

copy(1)  ifstream& operator= (const ifstream&) = delete;
move(2)  ifstream& operator= (ifstream&& rhs); 

等号运算符禁止使用左值引用,可以使用右值引用。(即右边的值必须是一个即将销毁的临时对象)

Public member functions inherited from istream

7,std::istream::operator>>

输入终端 cinifstream 都是 istream 的子类,所以输入操作符 >> 用法相同。对变量进入输入的时候重载了常用的数据类型。

arithmetic types (1)	
istream& operator>> (bool& val);
istream& operator>> (short& val);
istream& operator>> (unsigned short& val);
istream& operator>> (int& val);
istream& operator>> (unsigned int& val);
istream& operator>> (long& val);
istream& operator>> (unsigned long& val);
istream& operator>> (long long& val);
istream& operator>> (unsigned long long& val);
istream& operator>> (float& val);
istream& operator>> (double& val);
istream& operator>> (long double& val);
istream& operator>> (void*& val);stream buffers (2)	
istream& operator>> (streambuf* sb );manipulators (3)	
istream& operator>> (istream& (*pf)(istream&));
istream& operator>> (ios& (*pf)(ios&));
istream& operator>> (ios_base& (*pf)(ios_base&));

8,istream::gcount

streamsize gcount() const;

返回最后一个输入操作读取的字符数目。
可以修改这个返回值的函数有:get,getline,ignore,peek,read, readsome,putback and unget. 其中函数peek, putback and unget 被调用后gcount()返回值为0。

9,istream::get

single character (1): //读取一个字符,遇到'\n',也从流中取出。
int get(); //字符按 int 返回
istream& get (char& c); // 读到c中//读取n个 c 风格字符串到数组s中,遇到'\n'(或delim)停止读取,并把'\n'留在输入流中,若要读取多行,就要需要int get() 来取出'\n',才能读下一行。
c-string (2): 
istream& get (char* s, streamsize n);//默认delim是换行字符'\n'
istream& get (char* s, streamsize n, char delim) //指定读取停止字符 delimstream buffer (3):  //内容读取到 streambuf 对象中。
istream& get (streambuf& sb);//默认delim是换行字符'\n'
istream& get (streambuf& sb, char delim);//指定读取停止字符 delim

下面的程序演示get()读取到streambuf 的用法。

#include <iostream>     // std::cout, std::streambuf, std::streamsize
#include <fstream>      // std::ifstream
using namespace std;int main () {std::ifstream ifs ("test.txt");std::ofstream ofs ("out.txt");std::streambuf *pbuf = ofs.rdbuf();ifs.get(*pbuf);//默认读取截止字符是'\n', 所以读取一行停止,且没有读取'\n'。pbuf->sputc(ifs.get()); // '\n'并没有被读取到pbuf,所以需要get()来读取'\n',然后用函数sputc()加到 pbuf 中。ifs.get(*pbuf);  // 从流中取出了'\n' ,才能读取第二行pbuf->sputc(ifs.get());/*上面使用了函数 istream& get (streambuf& sb); 之后不能使用 istream& get (char* s, streamsize n);*/char s[20];       ifs.get(s,20);//虽然输入流有第三行,但是没法读取。cout<<"get:"<<s<<endl;  //内容为空ofs.close();ifs.close();return 0;
}

10,istream::getline

读取一行到字符数组。

istream& getline (char* s, streamsize n );
//默认delim是换行字符'\n',遇到后丢弃,第二次读取从delim后开始读。istream& getline (char* s, streamsize n, char delim );
//自己定义停止符delim

<string> 字符串头文件也定义了从流中读取一行的函数 getline()
因为它不是流的成员函数,所以不能通过点访问。

std::getline (string)

(1)	用户定义截止字符
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim); //c++11 标准(2)	截止字符默认'\n'
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str); // c++11 标准

用法:
从流对象is中读取一行存到字符串str 直到遇到截止字符,如果遇到截止字符,则把它从流中取出来,然后丢弃(它不被存储,下一个操作的起点在它之后)函数调用前str 中的内容将被覆盖。
demo: 读取文件流的内容

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{string str;ifstream ifs("test.txt");if(!ifs){cout<<"open file fail!"<<endl;return 1;}while( getline(ifs,str)){cout<<str<<endl;}return 0;
}

11,istream::ignore

istream& ignore (streamsize n = 1, int delim = EOF);

从输入流中读取n个字符并且丢弃,或者读到delim字符再停止读取。

12,istream::peek

int peek();

返回输入流下一个字符,并把它留在输入流中,作为下一次读取的起点。返回值是整形ascll码值,可以用 char© 转化为字符。

13,istream::read

istream& read (char* s, streamsize n);

从输入流中提取n个字符,并把他们存数组s中,不检测内容,也不加字符串结尾符号‘\0’,实例:

// read a file into memory
#include <fstream>  // std::ifstream
#include <iostream> // std::cout
#define LEN 10
int main() {char buffer[LEN];buffer[LEN - 1] = '\0';std::ifstream is("test.txt", std::ifstream::binary);if (is) {while (is) {is.read(buffer, LEN - 1);//最后一次读取长度小于 LEN-1时候,会打印一些无效的字符std::cout << "Reading " << is.gcount() << " characters. is:" << buffer<< std::endl;}is.close();}return 0;
}

14,istream::putback

istream& putback (char c);
// 用法,从输入流读取一个字符,再把它返回。
char c = std::cin.get(); 
std::cin.putback (c);

15,istream::unget

istream& unget();
// 返回最后一次读取的字符到输入流,类似putback()
char c = std::cin.get();
std::cin.unget();

16,istream::tellg

读取输入流中文件指针的位置,返回值可转化为 int。

streampos tellg();
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

17,istream::seekg

设定输入流中文件指针的位置。(1) 绝对位置 (2) 相对位置

(1)istream& seekg (streampos pos);
(2)istream& seekg (streamoff off, ios_base::seekdir way);

参数 pos 是流中的绝对位置可以转化为 int
参数 off 是偏移量,与way相关,类型是 int
参数 way 可以选下表中的任意一个常量。

valueoffset is relative to…
ios_base::begbeginning of the stream
ios_base::curcurrent position in the stream
ios_base::endend of the stream

Public member functions inherited from ios

18,ios::good

bool good() const;
bool eof() const;
bool fail() const;
bool bad() const;

检测流的状态是否正常。当错误的状态*flags (eofbit, failbit and badbit) *都没被设置的时候返回true
特定的错误状态可以用下面的函数(eof, fail, and bad)来检测。

iostate value (member constant)indicatesgood()eof()fail()bad()rdstate()
goodbitNo errors (zero value iostate)truefalsefalsefalsegoodbit
eofbitEnd-of-File reached on input operationfalsetruefalsefalseeofbit
failbitLogical error on i/o operationfalsefalsetruefalsefailbit
badbitRead/writing error on i/o operationfalsefalsetruetruebadbit

19,ios::operator!

bool operator!() const;
//Returns true if either failbit or badbit is set, and false otherwise.
// 有错误状态返回 trueint main () {std::ifstream is;is.open ("test.txt");if (!is)std::cerr << "Error opening 'test.txt'\n";return 0;
}

20,ios::operator bool

布尔运算: 当流对象单独出现在条件语句中时,就间接调用布尔运算。
如:if(ios), while(ios)
函数原型:
c++98: operator void*() const;
c++11: explicit operator bool() const;
返回值:failbit 或 badbit 都没被标记的时候返回真。
(对比good(): failbit 或 badbit 或 eofbit 都没被标记的时候返回真)
布尔运算一个很方便的用法就是检测文件结束。读到文件末尾的时候, eofbit, failbit 同时被设置为1,所以可以使用bool()来判断流的状态。
当文件打开失败的时候failbit 位被设置为1,所以也能检测打开是否成功。

//按行读文件,简洁的模板
#include<iostream>
#include<fstream>
#include<string>
using namespace std;void print_state (const std::ios& stream) 
{cout << "good()=" << stream.good();cout << " eof()=" << stream.eof();cout << " fail()=" << stream.fail();cout << " bad()=" << stream.bad()<<endl;
}
int main()
{string str;ifstream ifs("test.txt");if(ifs){//while( bool(getline(ifs,str)))// 等价//while( getline(ifs,str).good())//等价while( getline(ifs,str)){cout<<"line:"<<str<<endl;}}else{cout<<"open file fail!"<<endl;return 1;}print_state(ifs);return 0;
}

21,ios::rdstate

iostate rdstate() const;
// Returns the current internal error state flags of the stream.
// 返回当前流中的内部错误状态,iostate二进制数,需要做位运算来获取其相应位置上的值。
//这个函数的功能可以被 good(),eof(),fail(),bad() 替换。
int main () {std::ifstream is;is.open ("test.txt");if ( (is.rdstate() & std::ifstream::failbit ) != 0 )std::cerr << "Error opening 'test.txt'\n";return 0;
}





http://chatgpt.dhexx.cn/article/FF1B9HAc.shtml

相关文章

ifstream的使用

fstream提供了三个类&#xff0c;用来实现c对文件的操作。&#xff08;文件的创建、读、写&#xff09;。 ifstream – 从已有的文件读入 ofstream – 向文件写内容 fstream - 打开文件供读写 文件打开模式&#xff1a; ios::in 只读 ios::out 只写 ios::app 从文件末尾开始写&…

c++ 输入文件流ifstream用法详解

文章目录 c 输入文件流ifstream用法详解输入流的继承关系&#xff1a;C 使用标准库类来处理面向流的输入和输出&#xff1a;成员函数Public member functions1. **(constructor)**2. **ifstream::open**3. **ifstream:: is_open**4. **ifstream:: close**5. **ifstream:: rdbuf…

计算机工业控制高职教材,计算机控制技术(21世纪高职高专系列规划教材)

导语 本书以工业控制计算机(IPC)为主线&#xff0c;理论联系实际&#xff0c;突出工程应用&#xff0c;阐述了计算机控制技术及其工程实现方法。全书分为8章&#xff0c;内容包括&#xff1a;计算机控制系统概述&#xff0c;计算机控制过程通道&#xff0c;数字控制技术&#x…

高职高专信息工程学院专业设置

学院全面落实立德树人根本任务,注重实习实训,着力培养德才兼备的技能型信息技术人才。与华为、腾讯、百度、阿里巴巴、新浪、搜狐、网易等多家知名IT企业合作,建成多所紧贴行业前沿的实习实训基地,保证人才培养与企业需求无缝对接。学院现有计算机应用技术、云计算技术应用…

湖北省高职计算机本科学校有哪些,盘点最新湖北十大高职高专院校排名,湖北最好的高职院校有哪些?...

高职高专就是高等职业学院和高等专科学校的简称&#xff0c;是专科(大专)层次的普通高等学校。简单点来说&#xff0c;高职高专院校就是职业技术教育&#xff0c;是职业技术教育的高等阶段。今天小编就来给大家盘点下最新湖北十大高职高专院校排名&#xff0c;湖北最好的高职院…

江西省计算机学会高职高专,我校应邀出席江西省计算机学会高职高专工作委员会成立大会...

8月21日下午&#xff0c;江西省计算机学会高职高专工作委员会成立大会在南昌召开&#xff0c;中国计算机学会职业教育发展委员会、江西省计算机学会、广东省计算机学会高职高专分会、省内相关高职院校领导和企业代表等90余人参加成立大会。我校作为主任委员单位&#xff0c;副校…

武汉高职高专计算机专业分数线,武汉高职高专学校有哪些及分数线

武汉市高职高专众多&#xff0c;其中也包含不少野鸡大学&#xff0c;哪些高职高专是值得2020年高考生选择的正规高校&#xff0c;7月9日教育部官网已公布全国高校名单&#xff0c;其中武汉市有37所公办或民办的高职学校&#xff0c;已整理各高职院校2019年名单及最低录取分数线…

高职高专计算机毕业论文平面设计,高职高专平面设计论文

高职高专平面设计论文 1高职高专平面设计教学的问题 (1)学生学习态度不够端正 随着高校的不断扩招&#xff0c;大学本科的门槛变低&#xff0c;学习不好的学生也可以考上高职高专的&#xff0c;所以很多学生高中学习成绩就不好&#xff0c;基础不扎实&#xff0c;他们一直是态度…

计算机网络 高职,高职高专计算机网络

高职高专计算机网络 1、高职高专院校精品课程现状 从教学方法到教学手段、从教学思想到教学内容、从教材到管理、从教师到学生&#xff0c;计算机网络精品课程建设涉及广泛。然而&#xff0c;要想提升教学质量&#xff0c;就必须紧抓每一个环节。 1.1教学实践比重失衡 在现阶段…

湖北省高职高专计算机专业排名,湖北高职高专学校排名

今天就是高职高专院校填报志愿的日子了&#xff0c;湖北省的高职高专院校有哪些&#xff0c;排名比较靠前的是哪些&#xff0c;大家在填报志愿的时候总是非常迷茫不知道该填报什么专业&#xff0c;下面还给大家推荐了一些该院校的王牌专业&#xff0c;希望能对大家有所帮助。 周…

模式识别、机器学习、深度学习的区别

1、模式识别概念 模式识别是指对表征事物或现象的各种形式的(数值的、文字的和逻辑关系的)信息进行处理和分析&#xff0c;以对事物或现象进行描述、辨认、分类和解释的过程&#xff0c;是信息科学和人工智能的重要组成部分。 2、机器学习 计算机程序可以在给定某种类别的任…

什么是模式识别,对抗学习是什么?

模式识别是什么&#xff1f; 作为人工智能的一个重要方向&#xff0c;模式识别的主要任务是模拟人的感知能力&#xff0c;如通过视觉和听觉信息去识别理解环境&#xff0c;又被称为“机器感知”或“智能感知”。 人们在观察事物或现象的时候&#xff0c;常常要寻找它与其他事…

《模式识别与机器学习》 简称 PRML 开源了

前言 本文的原文连接是: https://blog.csdn.net/freewebsys/article/details/84847904 未经博主允许不得转载。 博主地址是&#xff1a;http://blog.csdn.net/freewebsys 1&#xff0c;关于PRML 《Pattern Recognition and Machine Learning》&#xff0c;中文译名《模式识别与…

关于机器学习、深度学习以及模式识别

随着这两年深度学习的火爆&#xff0c;在超分辨率重建领域也有着越来越多关于深度学习相关方法的文章涌现出来。对于之前没有接触过机器学习之类的人&#xff0c;看起来确实会有些一头雾水&#xff0c;所以这里整理了一下三个关于此的热词。深度学习、机器学习以及模式识别。 …

模式识别与机器学习第三章

一、线性判别函数 1.两类问题的判别函数 若这些属于ω1和ω2两类的模式可用一个直线方程 d(x)0 来划分&#xff0c;d(x) w1x1 w2x2 w3 0 d(x)称为两类模式的判别函数&#xff1b;d(x)0 称为决策面/判别界面方程。 用判别函数进行模式分类依赖的两个因素&#xff1a;&…

模式识别和机器学习 笔记

第一章 introduction 首先举了一个手写识别的例子&#xff0c;介绍了机器学习的基本概念&#xff1a;训练集、测试集合、训练阶段/学习阶段、泛化能力(generalization)、特征选择/抽取、监督式学习、 分类、回归、无监督式学习、聚类、密度估计、可视化、增强学习&#xff08…

机器学习,计算机视觉和模式识别分别有何联系?

目录 1. 定义1.0 模式识别&#xff1a;1.1 机器学习&#xff1a;1.2 计算机视觉&#xff1a; 2. 联系2.0 模式识别 vs 机器学习:2.1 模式识别 vs 计算机视觉: 3. 参考链接&#xff1a; 1. 定义 1.0 模式识别&#xff1a; The field of pattern recognition is concerned with …

模式识别/机器学习百题(含大部分答案)

一、概论 1、简述模式的概念和它的直观特性&#xff0c;解释什么是模式识别&#xff0c;同时绘出模式识别系统的组成框图&#xff0c;并说明各部分的主要功能特性。 对于存在于时间和空间中&#xff0c;可观察的物体&#xff0c;如果我们可以区分它们是否相同或相似&#xff…

模式识别与机器学习(国科大2021-2022秋季学期课程)-基础概念及算法

模式识别与机器学习-国科大2021-2022秋季学期课程 写在前面习题解答参考模式识别经典算法线性判别分析感知器算法&#xff08;赏罚机制&#xff09;贝叶斯决策问题贝叶斯最小错误率判别贝叶斯最小风险判别 正态分布模式的贝叶斯分类器线性判别函数 特征提取与降维PCA主成分分析…