文件操作(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命名空间内。
Type | Definition |
---|---|
ifstream | basic_ifstream |
wifstream | basic_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
发布评论