-1

I'm trying to open a zip archive in C++ using LibZip. Because I didn't find any working tutorials on that, I looked up the documentation and came to this code:

int err = 0;
zip_t *z = zip_open("file.zip", 0, &err);

zip_stat_t st;
zip_stat_init(&st);
cout << zip_stat(z, "file.zip", 0, &st) << endl;

cout << st.size << endl;

zip_close(z);

The problem is, that the zip_stat function returns -1 and the size of the file is zero. err always is 0, so I have no clue were the problem is. The code to get to the content would have looked like this:

char *contents = new char[st.size];

zip_file *f = zip_fopen(z, "file.zip", 0);
zip_fread(f, contents, st.size);
zip_fclose(f);

delete[] contents;

But obviously I couldn't test this part of the code yet. I'm using C++ 14 and LibZip 1.5.2

1 Answers1

3

zip_stat does not return information about a zip file, but about one of the entries inside a zip file. So unless your file.zip file contains another file also called file.zip your code is mistaken.

Maybe you really meant

cout << zip_stat(z, "data.zip", 0, &st) << endl;

since you seem to be trying to decompress a zip file entry called data.zip.

john
  • 85,011
  • 4
  • 57
  • 81
  • Ok, so how can I get the size of the compressed file, so that I can create a char array with the right size? –  Aug 09 '19 at 14:56
  • I don't think you understood what I said. – john Aug 09 '19 at 14:58
  • What's the name of your zip file? What's the name of the entry inside the zip file that you are trying to decompess? – john Aug 09 '19 at 14:59
  • I understand what you mean. I compressed a file.txt into file.zip, so know I need to check the size of the file.txt in the archive, right? Now I can read the content. –  Aug 09 '19 at 15:05
  • @Kuechenzwiebel That's right, I figured that out after you'd editted your question. – john Aug 09 '19 at 15:07
  • @Kuechenzwiebel And `zip_fopen` also needs the name "file.txt". – john Aug 09 '19 at 15:08
  • @Kuechenzwiebel And (in case it's not obvious) you shouldn't close the zip archive before you call `zip_fopen` (as the code above does). – john Aug 09 '19 at 15:12
  • Yes, I commented out the second part of the code, because it caused my program to crash and I was trying to get the size of the file first. –  Aug 09 '19 at 15:23