#include "stdafx.h"
#include <map>
#include <string>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <direct.h>
#include <chrono>
int main(){
FILE* fp;
// 1. 二进制打开图片文件
ifstream is("D:/workplace/test.jpg", ifstream::in | ios::binary);
// 2. 计算图片长度
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(0, is.beg);
// 3. 创建内存缓存区
char * buffer = new char[length];
// 4. 读取图片,放入缓存
is.read(buffer, length);
if (length>0)
// 到此,图片已经成功的被读取到内存(buffer)中
//以二进制写入方式
std::string file_name;
std::string strPicId;
GetUUID(strPicId);
file_name.append(strPicId);
file_name.append(".jpg");
std::int64_t curTime = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count() / 1000;
struct tm *t;
t = localtime(&curTime);
std::string file_path;
CConfigCenter::GetInstance().GetTomcatJpgUrl(file_path);
std::string pic;
char cFolderName[128] = { 0 };
char cTime[64] = { 0 };
sprintf(cFolderName, "%s/%d%02d%02d/", file_path.c_str(), t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
sprintf(cTime, "%d%02d%02d/", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
std::string strFolder = cFolderName;
strFolder.append(file_name);
FILE* fd = fopen(strFolder.c_str(), "wb+");
std::string strT = cTime;
if (fd != NULL)
{
std::string url;
CConfigCenter::GetInstance().GetWebPicUrl(url);
pic.append(url);
pic.append(strT);
pic.append(file_name);
LOG4CPLUS_INFO(LOGGERTAG, "读取图片大小:" << dwBufSize);
LOG4CPLUS_INFO(LOGGERTAG, "读取图片url:" << pic);
//从buffer中写数据到fp指向的文件中
fwrite(buffer, length, 1, fp);
//关闭文件指针,释放buffer内存
fclose(fp);
delete [] buffer;
is.close();
}
return 0;
}
fwrite函数就是写文件的函数,它的函数原型如下:
fwrite(const void *buffer, size_t size, size_t count , FILE *stream)
可以看到这个函数的参数有四个:
buffer : 数据存储的地址
size : 要读取的字节的大小
count : 要读取多少个size大小
stream : 等待被读取的数据源,它是一个指向FILE结构的文件指针