文件(含多级子目录)的打包和解包(下)
昨天七夕节,狗粮吃的饱饱哒。朋友圈秀恩爱的余波还未散尽,打算趁劲写完文件打包、解包这一专题(为什么?还用说,自然是吃饱才有力气干活啊,哈哈哈哈)
现在咱们说说解包,一个.dat文件,里面不知道包含了多少个文件/文件夹的信息,我们怎么解包呢?下面我们来回顾一下打包的过程:把文件/文件夹的外部信息(文件名、文件名长度、文件的长度)/(文件夹名、文件夹名长度、文件的长度、文件的相对路径信息、文件类型)以结构体的形式存放在.dat文件中,内容也保存到.dat文件中。
解包按打包接口参数:文件、文件夹的顺序读取内容即可,当然啦,两边的结构体信息要定义相同,这样大家的协议就一样,解包便不会出现问题了,代码如下:
1 bool UnPackFileAndDirectory(const string& inputzipfile, const string& outputpath) 2 { 3 FILE *rfp = NULL; 4 rfp = fopen(inputzipfile.c_str(), "rb"); 5 if (rfp == NULL) 6 { 7 cout << "解包:文件打开失败!" << endl; 8 return false; 9 } 10 11 //文件部分 12 int filecount; 13 fread(&filecount, sizeof(filecount), 1, rfp); 14 15 for (size_t i = 0; i < filecount; i++) 16 { 17 struct FileInfo packFile; 18 fread(&packFile, sizeof(packFile), 1, rfp); 19 20 cout << "filename:" << packFile.FileName << ", nameLen:" << packFile.fileNameLen << ", fileLen:" << packFile.fileSize << endl; 21 string path_file = outputpath + '\\' + packFile.FileName; //path_file:全路径 22 23 FILE *unpackFile = NULL; 24 unpackFile = fopen(path_file.c_str(), "wb"); 25 if (unpackFile == NULL) 26 { 27 cout << "文件:文件创建失败!" << endl; 28 } 29 30 unsigned char*tmpBu = new unsigned char[packFile.fileSize]; 31 fread(tmpBu, packFile.fileSize, 1, rfp);//当然也可以不借助缓冲区 32 fwrite(tmpBu, packFile.fileSize, 1, unpackFile); 33 34 } 35 cout << endl; 36 37 //文件夹部分 38 int folderCount; 39 fread(&folderCount, sizeof(folderCount), 1, rfp); 40 41 for (size_t i = 0; i < folderCount; i++) 42 { 43 struct FolderInfo folder; 44 fread(&folder, sizeof(folder), 1, rfp); 45 46 //文件夹的基本信息 47 cout << "FolderName:" << folder.FolderName << ", nameLen:" << folder.FolderNameLen << ", FolderSize:" << folder.FileSize << ", path:" << folder.Filepath << ", type:" << folder.type << endl; 48 49 string path_folder = outputpath + '\\' + folder.Filepath; //解包后全路径 50 const char * Lpath = path_folder.c_str(); 51 52 if (folder.type == 0 ) //文件类型 53 { 54 FILE * unpackFolders = NULL; 55 unpackFolders = fopen(path_folder.c_str(), "wb"); 56 if (unpackFolders == NULL) 57 { 58 cout << "文件夹:子文件创建失败!" << endl; 59 } 60 61 unsigned char*readFolder = new unsigned char[folder.FileSize]; 62 fread(readFolder, folder.FileSize, 1, rfp); 63 fwrite(readFolder, folder.FileSize, 1, unpackFolders); 64 65 } 66 if (folder.type == 1)//文件夹类型 67 { 68 ::CreateDirectory(Lpath, NULL); //创建文件夹 69 } 70 } 71 72 return true; 73 }
之前有位大神在我博文下评论,说我new的空间没有释放,get到了,大家不要跟我一样粗心哦~
文件打包解包这一专题终于写完了,好开心呀。有需要改进完善的地方欢迎大家提出宝贵意见,膜拜各位大佬 …