最近学C++的时候想了个问题,能否将文件或图片转换成二进制的字符串,
然后在需要的时候将二进制数据转换成文件能,这样就相当于模拟了文件上传的过程,
希望有源码配上详细的注释
include include
using namespace std;
int main()
{
char buffer[256];
ifstream examplefile ("D:temp.txt");
if (! examplefile.is_open())
{
cout << "Error opening file"; return -1;
}
while (! examplefile.eof() )
{
examplefile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
using namespace std;
int main()
{
char buffer[256];
ifstream examplefile ("D:temp.txt");
if (! examplefile.is_open())
{
cout << "Error opening file"; return -1;
}
while (! examplefile.eof() )
{
examplefile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
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;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。