文本文件保存为二进制文件

bool cFileCtrl::saveFile()
{
 ofstream binfile("packUI.bin",ios::binary); 
 for ( unsigned int i = 0; i < allFileName.size(); i++)
 {
   FILE* stream; 
   string fileString = '$'+ allFileName[i].cPath+ '$';

   if( (stream  = fopen( allFileName[i].cPath.c_str(), "r+b" )) == NULL )
   {
    printf( "The bin file %s was not opened/n", allFileName[i].name.c_str() );
    return false;
   }
   else
   {
    fseek(stream, 0, SEEK_END);    
    long length = ftell(stream);
    char* allc = (char*)malloc(length);
    memset(allc, 0, length);
    fseek(stream, 0, SEEK_SET);   
    char fileLeng[8] = {0};
    sprintf(fileLeng, "%d", length);
    fileString = fileString + fileLeng;
    fileString = fileString + "$";

    int tt = 0;

    char* p = allc;
    while( !feof( stream ) )
    {
     char buf[128];
     ZeroMemory( buf, 128);
     tt = fread(buf, sizeof(char), 100, stream);
     memcpy(p, buf, tt);
     p += tt;
    }
    binfile.write(fileString.c_str(),fileString.length());
    binfile.write(allc,length);    
    free(allc);
   }
   fclose( stream );
 }
 return true;
}

你可能感兴趣的:(文本文件保存为二进制文件)