C++ 文件流的方式操作文件(一个简单的写入,读取)

  新手学习c++哈,归纳的写了一下以 C++ 的方式写入读取文件,读文件到控制台,并加了行号。博客记录主要为了备忘。当然 ^_^ 喜欢同学的话可以拿走代码直接用。转帖注明出处哈。欢迎讨论,我一直认为:知识是通过不断的探讨,学习,研究,质疑才能进行升华,提升的。

#include <iostream>    
#include <fstream>
using namespace std;
// 文件操作
class CFileOper
{

	fstream m_pstrFile;
public:
	CFileOper(const char *cFileDir)
	{
		try
		{
			m_pstrFile.open(cFileDir, ios::binary | ios::out | ios::in);
			if (!m_pstrFile.is_open())
			{
				throw "文件打开失败";
			}
		}
		catch (const char * ErrorInfo)
		{
			cout << ErrorInfo;
		}
	}

	void writeDataToFile(char *cData, const int &nDataCount)
	{
		for (int i = 0; i < nDataCount; i++)
		{
			// m_pstrFile << cData[i] << endl; // 每遇到endl 引发一次同步,这种方式是不是会增加IO ?还是使用手动吧
			m_pstrFile << cData[i] << "\n";
		}
		// 手动引发同步
		m_pstrFile.sync();
	}

	void printFile(const char *cFileDir)
	{

		if (!m_pstrFile.is_open())
		{
			cout << "Error opening file"; exit(1);
		}

		int tellg = m_pstrFile.tellg();
          // 判断文件指针是否在开头 if (tellg != 0) { // 指针不在文件的开头,重置指针位置 m_pstrFile.seekg(0, ios::beg); } int i = 1; while (!m_pstrFile.eof()) { // 读取每一行的数据到缓冲区 char content[200] = { 0 }; m_pstrFile.getline(content, 100); cout << i << " :" << content << endl; i++; } } virtual ~CFileOper() { m_pstrFile.close(); } }; int _tmain(int argc, _TCHAR* argv[]) { CFileOper fileObj("test.txt"); // 写入数据 char cContent[] = { "hello word" }; fileObj.writeDataToFile(cContent, _countof(cContent)); // 读取数据 fileObj.printFile("test.txt"); return 0; }

  小记: 在文件的读的时候遇到了一些的困扰,主要问题来源于文件指针判断是否在开头的地方判断失败,以至于一直认为文件需要关闭后再次打开,并重新实例化才可以使用

当然这样肯定是很蠢的做法。在不懈的努力与求解下,发现了问题的根源

int tellg = m_pstrFile.tellg();
if (tellg != 0)  // 这个是正解。之前错误的写法是 if(m_pstrFile.tellg() != 0) 当然这样写的话会发现是报错的!

  这个东西……tellg() 这个函数,通过查看原型,最后发现他是由模板实现的。而且返回值的类型也不是一个直接可用的int。

  所以最后我用了一个int 类型的变量接收了它的返回值。然后就可用了。当然后续也试了一下 (int)tellg() 这样强转,也是可行的。

  目前存在的疑惑是:文件过大的话,如果用 int 去接收这个函数的返回值。返回的大小会不会造成溢出。是不是需要用long来进行接收……

猜你喜欢

转载自www.cnblogs.com/catshadow/p/9079085.html