最近學C++的時候想了個問題,能否將文件或圖片轉換成二進制的字符串,
然後在需要的時候將二進制數據轉換成文件能,這樣就相當於模擬了文件上傳的過程,
希望有源碼配上詳細的注釋
void WriteFromStream(char * buf,char * filename,UINT size)
{
FILE * f = fopen(filename,"wb+");
if (f)
{
fwrite(buf,1,size,f);
fclose(f);
}
}
void ReadToStream(char * filename)
{
FILE * f = fopen(filename,"rb");
if (f)
{
fseek(f,0,SEEK_END);
int size = ftell(f);
char * buf = new char[size];
fseek(f,0,SEEK_SET);
memset(buf,0,size);
int nRead = fread(buf,sizeof(char),size,f);
fclose(f);
if (nRead > 0)
{
//將二進制流打印成16進制字符串
for(unsigned int i = 0; i < nRead;i++)
{
printf("%02X ",(unsigned char)buf[i]);
if (i%16 == 15)
{
printf("\n");
}
}
}
char new_file[MAX_PATH] = "";
sprintf(new_file,"new_%s",filename);
WriteFromStream(buf,new_file,size);
WinExec("explorer .",SW_SHOW);
delete buf;
}
}
int main(int argc,char **argv)
{
ReadToStream("temp.zip");
return 0;
}