C++11 文件操作(1)读文件ifstream

编程入门 行业动态 更新时间:2024-10-26 08:27:36

C++11 <a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件操作(1)读文件ifstream"/>

C++11 文件操作(1)读文件ifstream

今天我们的操作都是基于std::ifstream,但我们要从另外一个东西谈起: std::basic_ifstream

#include <fstream>
template<class CharT,class Traits = std::char_traits<CharT>
> class basic_ifstream : public std::basic_istream<CharT, Traits>

basic_ifstream实现了基于文件流的输入操作,第一个模板参数类型指定了以什么为单位来读取流。

而ifstream是该模板类的一个实例化,指定了按char类型来读取流。定义于头文件 <fstream>的std命名空间内。

TypeDefinition
ifstreambasic_ifstream
wifstreambasic_ifstream<wchar_t>

按行读取

#include <iostream>  
#include <fstream>  int main() {char buffer[256];std::ifstream in("./111.txt");if (!in.is_open()){std::cout << "Error opening file"; exit(1);}while (!in.eof()){in.getline(buffer, 100);std::cout << buffer << std::endl;}return 0;
}

is_open 判断文件流是否和文件关联 ,可以用来检测文件是否打开成功。
eof用来检测是否到达文件末尾。

额外介绍下getline

basic_istream& getline( char_type* s, std::streamsize count );
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );
  • 第一个函数等价于getline(s, count, widen(‘\n’)),从输入流读取一行数据到传入的buffer,也就是第一个参数,第二个参数指定了buffer的大小。

在遇到换行符或者读取的数据已经达到指定数目count-1(预留一个用来存放\0),停止读取。

  • 第二个函数的第三个参数用于指定终止符。

任意字节读取

basic_istream& read( char_type* s, std::streamsize count );

需要注意的是,它的返回值不像C函数是读到的字节数,而是文件流自身,以实现连续操作。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>int main()
{// read() is often used for binary I/Ostd::string bin = {'\x12', '\x12', '\x12', '\x12'};std::istringstream raw(bin);std::uint32_t n;if(raw.read(reinterpret_cast<char*>(&n), sizeof n))std::cout << std::hex << std::showbase << n << '\n';// prepare file for next snippetstd::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";// read entire file into stringif(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {auto size = is.tellg();std::string str(size, '\0'); // construct string to stream sizeis.seekg(0);if(is.read(&str[0], size))std::cout << str << '\n';}
}

更多推荐

C++11 文件操作(1)读文件ifstream

本文发布于:2024-02-10 20:16:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   操作   ifstream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!