1

I am trying to unzip a .zip file, at a specified location. The user inputs the name of the file to be unzipped like "D:\\folder\\sample.zip". I am making use of zip headers and .cpp files from this link https://www.codeproject.com/articles/7530/zip-utils-clean-elegant-simple-c-win

Now below is my code

int main()
{
    char filename[100];
    HZIP hz; DWORD writ;
    printf("Enter filename: \n");
    gets(filename);
    TCHAR *name = (TCHAR *) filename;
    hz = OpenZip(name,0);
    SetUnzipBaseDir(hz,_T("D:\\unzipped\\"));
    ZIPENTRY ze; 
    GetZipItem(hz,-1,&ze); 
    int numitems=ze.index;
    for (int zi=0; zi<numitems; zi++)
    {
        GetZipItem(hz,zi,&ze);
        UnzipItem(hz,zi,ze.name);
    }
    CloseZip(hz);
    printf("Unzipped\n");   
    return 0;
}

I need the filename to be taken as input from the user, for which I had to typecast it by using this statement

TCHAR *name = (TCHAR *) filename;

But this is the statement that is causing problems now. When I debugged the program and added watch to the variable 'name', I saw that after typecasting, it stored some Chinese letters, instead of the path of the zip file

Previously the code worked fine when instead of taking input from user, I hardcoded the path and file name as mentioned below

hz = OpenZip(_T("D:\\folder\\sample.zip"),0);

Any ideas what am I doing wrong?

user52327
  • 13
  • 4

1 Answers1

0

The Windows file systems (NTFS, FAT32) encode file names in Unicode (UTF16). That is why the OpenZip API expect a wchar_t* (string of wide characters) as the file name parameter.

The C++ standard provides a wstring class similar to the ANSI string (or C string) that is supposed to contain Unicode characters, and a wcin and wcout streams for input/output in Unicode encoding.

wstring wfilename; 
std::wcin >> wfilename;
OpenZip(wfilename.c_str(), 0); // c_str() retrives the wchar_t* in the buffer, much similarly to the ANSI `string.

EDIT: Since you need to input into a C-style buffer, here is the easiest way to convert a C-style char[] to wstring and wchar_t[]:

char filename[100]; printf("Enter filename: \n");   cin >> filename;

// conversion
std::wstring wFilename(strlen(filename), L' ');
std::copy(filename, filename + wFilename.length(), wFilename.begin());


OpenZip(wFilename.c_str(), 0);
A.S.H
  • 29,101
  • 5
  • 23
  • 50