c/c++读写照片、传输文件方式
测量耗时时间可用计时器: 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