首页 技术 正文
技术 2022年11月21日
0 收藏 359 点赞 3,870 浏览 1582 个字

  新手学习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来进行接收……

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,360
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,852