c/c++读写照片、传输文件方式

本文介绍了C/C++中进行文件读写和传输的不同方法,包括运行库调用、API直接操作以及使用ifstream和ofstream。详细讨论了fopen、fread、fwrite等函数的API调用,以及如何使用CreateFile、ReadFile和WriteFile进行高效操作。同时,文章提到了安全性和解决fopen警告的方法。
摘要由CSDN通过智能技术生成

测量耗时时间可用计时器: StopWach链接

运行库接口内部实现是对API的调用,如:
std::fopen 实际调用的API: CreateFile
std::fread 实际调用的API: ReadFile
std::fwrite 实际调用的API: WriteFile

运行库调用

seekg()对文件定位,有两个参数:偏移量和基地址。
偏移量:正负数值,正的表示向后偏移,负的表示向前偏移
基地址:表示输入流的位置,3种表示:
ios::beg:开始位置
ios::cur:当前位置
ios::end:结束位置
tellg()函数无参数,返回当前定位指针的位置,也代表着输入流的大小。
“error C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead” 解决方法

#include <fstream> // ifstream, ifstream::in
#include <iostream>
void WritePicture(std::string path, char* cContent, int ilength)
{
   
	FILE* pw;
	pw = std::fopen(path.c_str(), "wb");
	fwrite(cContent, sizeof(char), ilength, pw);
	fflush(pw);
	fclose(pw);
}
void ReadWritePicture(const std::string& szReadPath, const std::string& szWritePath)
{
   
	// 1. 打开图片
	std::ifstream iPicture(szReadPath, std::ifstream::in | std::ios::binary);
	// 2. 计算图片长度
	iPicture.seekg(0, iPicture.end);    //基地址为结束位置,偏移量为0
	int length = iPicture.tellg();
	iPicture.seekg(0, iPicture.beg);     //基地址为结束位置,偏移量为0
	// 3. 创建内存缓存区
	char* cCache = new char[length];
	if (nullptr == cCache)
	{
   
		return;
	}
	// 4. 读取图片到内存中
	iPicture.read(cCache, length);
	iPicture.close();
	WritePicture(szWritePath, cCache, length);
	delete[] cCache;
	cCache = nullptr;
}
int main() {
   
	std::string szReadPath = "test.png";
	std::string szWritePath = "image.png";
	ReadWritePicture(szReadPath, szWritePath);
	return 0;
}
#include <fstream> // ifstream, ifstream::in
#include <iostream>
void ReadPicture(const std::string& szReadPath, std::string& szContent, int& ilength)
{
   
	// 1. 打开图片
	std::ifstream iPicture(szReadPath, std::ifstream::in | std::ios::binary);
	// 2. 计算图片长度
	iPicture.seekg(0, iPicture.end
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qzy0621

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值