Creation archive problem using libzip and C

355 Views Asked by At

Im trying to create program for building archives using libzip and C. Function below must create archive from files. Name of directory with files and name of output file passed as a command line arguments. Code works without any errors. The main problem that program does not create a .zip file, and I don`t understend why.

#include <zip.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <string.h>

static bool is_modified (char *filename);

static void create_zip (char *source_name, char *output_filename, char *dir_name)
{
    int err = 0;

    DIR *dir = opendir(dir_name);//open directory
    struct dirent *entry;

    if(!dir){
         fprintf(stderr, "Cannot read directory\n");
         exit(1);
    }
    fprintf(stdout, "DIR - [%s]\n", dir_name);

    zip_t *archive_zip = zip_open(output_filename, ZIP_CREATE, &err);//create zip
    if(archive_zip == NULL)
    {
        zip_error_t ziperr;
        zip_error_init_with_code(&ziperr, err);
        fprintf(stderr, "Failed to create archive, error -[%i]\n", err);
        zip_close(archive_zip);
        exit(1);
    }else
        printf("Archive [%s] created\n", output_filename);

    while((entry = readdir(dir)) != NULL)// walking through directory
    {
        if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, source_name) !=0)
        {
            zip_source_t *source = zip_source_file(archive_zip, entry->d_name, 0, 0);//creating source for every file in dir
            if(source == NULL)
            {
                fprintf(stderr, "Cant create source file [%s]\n", entry->d_name);
            }
            if(zip_file_add(archive_zip, entry->d_name, source, ZIP_FL_OVERWRITE) < 0)// adding it to archive with overwrite flag
            {
                zip_source_free(source);
                fprintf(stderr, "Cant add file [%s]\n", entry->d_name);
            }else
                fprintf(stderr, "File [%s] added\n", entry->d_name);
        }
    }
    zip_close(archive_zip);
    closedir(dir);
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <output_file> <input_dir_name>\n", argv[0]);
        return 1;
    }
    create_zip(argv[0],argv[1], argv[2]);
    return 0;
}


Output looks like

DIR - [test_dir]
Archive [test] created
File [f1.txt] added
File [f2.txt] added

Thank you for help).

0

There are 0 best solutions below