Search code examples
zipcompressiongnomevala

Vala: How to retrieve the names of all files in a zip archive without unzipping it?


Is there any function in vala like zip:list_dir in erlang ? I found libgsf, but I don't want to decompress the zip file.


Solution

  • You can use libarchive.

    void check_ok (Archive.Result r) throws IOError {
        if (r == Archive.Result.OK)
            return;
        if (r == Archive.Result.WARN)
            return;
        throw new IOError.FAILED ("libarchive returned an error");
    }
    
    int main () {
    
        try {
            var a = new Archive.Read ();
            check_ok (a.support_filter_all ());
            check_ok (a.support_format_all ());
            check_ok (a.open_filename ("archive.zip", 10240));
    
            unowned Archive.Entry entry;
            while (a.next_header (out entry) == Archive.Result.OK) {
                stdout.printf ("%s\n", entry.pathname ());
                a.read_data_skip ();
            }
        }
        catch (IOError e) {
            stderr.printf (e.message + "\n");
            return 1;
        }
    
        return 0;
    }
    

    Compile with valac ListZip.vala --pkg libarchive --pkg gio-2.0.

    GIO is only needed for the IOError errordomain. In reality, you'd want to extend the check_ok method with some more descriptive message which operation has failed.

    You can also restrict libarchive to only allow zip files. I have translated the example from the upstream wiki.