c++ IO库之ifstream的一些基本操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ypy9323/article/details/81813622

       c++ IO库中关于文件的的流有六个,它们是ifstream wifstream ofstream wofstream fsream wfsream。w开始的是针对wchar_t类型的数据。从左到右分为三组,它们作用分别是:从文件读取数据、向文件写入数据、读写文件。它们包含在fstream头文件中最近在项目中用到了ifstream,现在对其进行简要说明。                       

       ifstream 类可以读取文本文件、图片文件。怎样读取文件呢?往下看。

       1>构造一个ifstream对象,并按指定方式打开文件:

           explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);

           参数一:文件路径

           参数二: 打开方式

      2>设置将要提取字符的位置

         istream& seekg (streamoff off, ios_base::seekdir way);

         参数一:相对参数二偏移量

         参数二:位置指示有三个:  ios_base::beg(文件的开始处), ios_base::cur(当前位置), ios_base::end(文件结尾)

     3>返回流中当前字符的位置

         streampos tellp();

         返回值:

                 定位失败返回-1;

                 成功当前(seekg()函数定位的位置)字符位置。【注】这个返回值也意味着开始到当前位置的长度。

示例代码如下:

   

#include <QtCore/QCoreApplication> 
#include <fstream>  // ifstream 头文件; 
#include <string>
#include <iostream>

/**
 *参数: 文件路径;
 */
void fstream_read_text(const std::string& str_path) 
{
	using std::ifstream;

	// [1]构建对象,并以二进制形式打开;
	ifstream i_f_stream(str_path, ifstream::binary);
	// [2]检测,避免路径无效;
	if (!i_f_stream.is_open()) {
		return;
	}
	// [3]定位到流末尾以获得长度;
	i_f_stream.seekg(0, i_f_stream.end);
	int length = i_f_stream.tellg();
	// [4]再定位到开始处进行读取;
	i_f_stream.seekg(0, i_f_stream.beg);

	// [5]定义一个buffer;
	char *buffer = new char[length];
	// [6]将数据读入buffer;
	i_f_stream.read(buffer, length);

	// [7]记得关闭资源;
	i_f_stream.close();

	std::cout.write(buffer, length);

	delete[] buffer;
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	fstream_read_text(std::string("E:/test.txt"));

	return a.exec();
}

  上述代码读取了一个txt文件,下篇文章将介绍用ifsream读取图片文件并用Qt类检测读取结果。

猜你喜欢

转载自blog.csdn.net/ypy9323/article/details/81813622