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;

}

相关推荐
Rabitebla7 分钟前
C++ 入门基础:从 C 到 C++ 的第一步
c语言·开发语言·c++
Greedy Alg9 分钟前
定长内存池学习记录
c++·后端
西魏陶渊明9 分钟前
解决异步挑战:Reactor Context 实现响应式上下文传递
开发语言·python
小则又沐风a14 分钟前
C++内存管理 C++模板
开发语言·c++
不会写DN14 分钟前
如何给 Go 语言的 TCP 聊天服务加上 ACK 可靠送达机制
开发语言·tcp/ip·golang
小李云雾18 分钟前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
llm大模型算法工程师weng24 分钟前
Python敏感词检测方案详解
开发语言·python·c#
fengci.25 分钟前
php反序列化(复习)(第二章)
android·开发语言·学习·php
ZHENGZJM27 分钟前
后端基石:Go 项目初始化与数据库模型设计
开发语言·数据库·golang
拾贰_C28 分钟前
【Claude Code | bash | install】安装Claude Code
开发语言·bash