开发者社区> 问答> 正文

C++将文件转换成二进制数据流

最近学C++的时候想了个问题,能否将文件或图片转换成二进制的字符串,
然后在需要的时候将二进制数据转换成文件能,这样就相当于模拟了文件上传的过程,
希望有源码配上详细的注释

展开
收起
a123456678 2016-03-06 16:39:21 5718 0
3 条回答
写回答
取消 提交回答
  • 乐于学习与分析

    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;
    }

    2019-07-17 18:54:50
    赞同 展开评论 打赏
  • 软件开发,安全加密

    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;
    }

    2019-07-17 18:54:50
    赞同 展开评论 打赏
  • 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;
        }
    2019-07-17 18:54:50
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载