c++ ofstream 和ifstream 读写二进制文件的简单操作

主要使用ofstream 和ifstream 的技术 纯c++实现

有时间感觉使用qt的文件操作没有c++的适用 特别是遇到中文或者\0 的特殊字符时 还是c++有效

void WriteFile(const string & sFilePath, const string & sContent)

{

ofstream out(sFilePath.c_str(), ios::binary);

if (out.is_open())

{

out.write(sContent.c_str(), sContent.size());

out.close();

}

return;

}

void ReadFile(const string & sFile, string & sContent)

{

ifstream in(sFile, ios::binary);

if (!in.is_open())

{

cout << "Error opening file"; exit(1);

}

in.seekg(0, ios::end);

int isize = in.tellg();

in.seekg(0, ios::beg);

unsigned char *pBuf = new unsigned char[isize];

in.read((char *)pBuf, isize);

copy(pBuf, pBuf + isize, back_inserter(sContent));

if (nullptr != pBuf)

{

delete [] pBuf;

pBuf = nullptr;

}

return;

}

相关推荐
感哥14 小时前
C++ 面向对象
c++
沐怡旸16 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥1 天前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸2 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥2 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++