场景:读取大数据文件的时候,可以以一个固定大小的buff分多次读取文件,每读取一个buff,就把它存入到一个std::string中,并写入到新的文件中。直到读完文件,同时关闭文件。
<pre name="code" class="cpp">// test_write_file.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <wchar.h>
#include <io.h>
using namespace std;
void testWriteImageDataToBinaryFile()
{
std::string str;
FILE* wfile;
wfile =_wfopen(L"E:\\15.txt",L"wb");
//从文件中读数据
FILE *rfile =_wfopen(L"E:\\IMG_2314.JPG",L"rb");
fseek(rfile,0,SEEK_END);
unsigned int size =ftell(rfile);
unsigned int buff[1024];
unsigned int count =size/1024;
unsigned int temp_size =count%1024;
for(unsigned int i = 0;i<count;++i)
{
fread(buff,1024,1,rfile);
//存到一个std::string里
//写人数据到文件中
str.append((const char*)buff,1024);
fwrite(str.data(),str.size(),1,wfile);
str.clear();
}
if(temp_size>0)
{
//写人数据到文件中
fread(buff,temp_size,1,rfile);
str.append((const char*)buff,temp_size);
fwrite(str.data(),str.size(),1,wfile);
str.clear();
}
fclose(rfile);
fclose(wfile);
}
int _tmain(int argc, _TCHAR* argv[])
{
testWriteImageDataToBinaryFile();
return 0;
}
[C/C++]_[初级]_[把一个图片的数据存入到std::string里,使用_wfopen生成二进制文件]
最新推荐文章于 2023-04-19 01:03:43 发布