Files
MyZip/MyZip.cpp
T
2026-08-31 16:51:47 +09:00

168 lines
5.8 KiB
C++

#include <Windows.h>
#include <filesystem>
#include <debugapi.h>
#include "MyZip.h"
// Phase A(AddFileToZip) / Phase B(FinalizeZip) 구조:
// - AddFileToZip() : 파일 하나 읽어서 [LocalFileHeader][파일명][데이터]를 fileOut에 이어 쓰고,
// 이 파일의 CentralDirectory 정보는 vecEntries에 누적만 해둠 (아직 안 씀).
// - FinalizeZip() : 전체 순회가 끝난 뒤 딱 한 번 호출. 누적된 CentralDirectory들을 순서대로 쓰고,
// EOCD 작성 후 스트림을 닫음.
// Phase A
// - strFilePath 파일을 열어 크기 계산 + CRC 계산
// - LocalFileHeader 채워서 [헤더][파일명][데이터] 순서로 fileOut에 씀
// - 이 파일의 CentralDirectory를 채워서 vecEntries에 push_back
// - 이 시점에는 CentralDirectory/EOCD를 파일에 쓰지 않음 (Finalize 단계)
bool MyZip::AddFileToZip(const std::string & strFileDiskPath, const std::string& strFileEntryPath)
{
std::ifstream fileIn(strFileDiskPath, std::ios::binary);
if (!fileIn.is_open())
{
printf("[ ERROR ](AddFileToZip) Something went Worng...");
printf("fileIn open failed");
return false;
}
// 파일 크기 계산
fileIn.seekg(0, std::ios::end); // seekg (offset, 목표점)
std::streamsize fileInSize = fileIn.tellg();
fileIn.seekg(0, std::ios::beg); // beg == begin
// 메모리 할당
std::vector<uint8_t> fileInBuffer(fileInSize);
// TODO : Buffering 으로 구현. 현재는 파일 통짜로 읽음.
char *pInBuffer = reinterpret_cast<char *>(fileInBuffer.data());
// 파일 읽기
if (!fileIn.read(pInBuffer, fileInSize))
{
printf("[ ERROR ](AddFileToZip) Something went Worng...");
printf("fileIn read failed");
return false;
}
// Gathering data
uint32_t myCRC = getCRC32(pInBuffer, fileInSize);
uint16_t fileNameLeng = static_cast<uint16_t>(strFileEntryPath.length());
////////////////////////////////////////////////////////////////////////////////////////
LocalFileHeader LFHeader{};
CentralDirectory CentDir{};
// LocalFile Header
FillLocalFileHeader(LFHeader, myCRC, static_cast<uint32_t>(fileInSize), fileNameLeng);
// CentralDirectory Header
CentralDirectory fiiledCDH = GetFilledCentDirHeader(CentDir, myCRC, static_cast<uint32_t>(fileInSize), fileNameLeng);
// LocalFile Header 의 시작위치
fiiledCDH.offsetLocalFileHeader = static_cast<uint32_t>(fileOut.tellp());
// 우선 CDH 는 vector 에 저장 (나중에 파일 쓸 때 마저 채움.)
vecEntries.push_back({fiiledCDH, strFileEntryPath });
// 1. Local File Header, file name (var), extra field (var)
fileOut.write(reinterpret_cast<const char *>(&LFHeader), sizeof(LFHeader));
fileOut.write(strFileEntryPath.c_str(), LFHeader.lengthOfFileName);
// fileOut.write(NOT_USED, LFHeader.lengthOfExtraField);
// 2. File Data
fileOut.write(pInBuffer, fileInSize);
// TODO : 성공여부 처리 어떻게 할 건지?
return true;
}
// Phase B
// - vecEntries를 순서대로 순회하며 [CentralDirectory][파일명] 씀
// - EoCDRecord 채우기 (numOfEntries = vecEntries.size() 등 누적값 반영)
// - EoCDRecord 쓰기 -> fileOut.close()
bool MyZip::FinalizeZip()
{
bool iRet = false;
iRet = fileOut.is_open();
if (!iRet)
{
printf("[ ERROR ](FinalizeZip) Something went Worng...");
printf("FileOut open failed");
}
else
{
// TODO : EOCDR Temp format 채우기.
this->EOCDR.diskNumber = 0; // Temp
this->EOCDR.diskNumber_CentralDirStart = 0; // Temp
this->EOCDR.numOfCentralDir = static_cast<uint16_t>(vecEntries.size());
this->EOCDR.numOfEntries = static_cast<uint16_t>(vecEntries.size());
this->EOCDR.lengthOfCommentLength = 0;
for (const auto &p : vecEntries)
{
this->EOCDR.sizeOfCentralDir += (sizeof(p.header) + p.header.lengthOfFileName);
}
this->EOCDR.offsetCentralDir = static_cast<uint32_t>(fileOut.tellp());
// Write to file (archiving)
for (const auto &p : vecEntries)
{
// CentralDirectory, file name (var)
fileOut.write(reinterpret_cast<const char *>(&p.header), sizeof(p.header));
fileOut.write(p.fileName.c_str(), p.header.lengthOfFileName);
}
// End of CentralDirectory Record
fileOut.write(reinterpret_cast<const char *>(&this->EOCDR), sizeof(this->EOCDR));
fileOut.close();
}
// TODO : 성공여부 처리 어떻게 할 건지?
return iRet;
}
void MyZip::FillLocalFileHeader(LocalFileHeader &targetLF, const uint32_t targetCRC, const uint32_t targetSize, const uint16_t targetNameLeng)
{
// ZIP 포맷 채워넣기
// Put PK Signature
targetLF.signature = PK_SIGNATURE_LF_HEADER;
// TOOD : Temp Format 채우기.
targetLF.versionNeededToExtract = 0; // Temp
targetLF.generalBitFlag = 0; // Temp
// Put compressed method (uncompressed)
targetLF.compressionMethod = METHOD_UNCOMPRESSED;
// lastMode[Time|Date] => Not Used.
// Put CRC value
targetLF.crc32 = targetCRC;
// Put File size
targetLF.sizeOfUncompressed = targetSize;
targetLF.sizeOfCompressed = targetLF.sizeOfUncompressed;
// Put File name length
targetLF.lengthOfFileName = targetNameLeng;
// Extra Field 는 사용하지 않음
// LFHeader.lengthOfExtraField = NOT_USED;
}
CentralDirectory MyZip::GetFilledCentDirHeader(CentralDirectory &targetCDH, const uint32_t targetCRC, const uint32_t targetSize, const uint16_t targetNameLeng)
{
targetCDH.crc32 = targetCRC;
targetCDH.sizeOfUncompressed = targetSize;
targetCDH.sizeOfCompressed = targetCDH.sizeOfUncompressed;
// Put File name length
targetCDH.lengthOfFileName = targetNameLeng;
// Extra Field 는 사용하지 않음
// targetCDH.lengthOfExtraField = NOT_USED;
// TODO : targetCDH Temp format 채우기.
targetCDH.lengthOfFileComment = 0;
targetCDH.diskNumStart = 0; // Temp
targetCDH.attributeInternal = 0; // Temp
targetCDH.attributeExternal = 0; // Temp
// targetCDH.offsetLocalFileHeader -> 실제 파일 Write 중에 작성.
return targetCDH;
}