Tutorials

Page last edited 3,610 days ago
From Shakasulik
Jump to navigation Jump to search

About[edit | edit source]

The tutorials will guide you on how to:

  1. Compile different libraries from source using Visual Studio 2013
  2. Use the libraries and headers in a simple C++ project

Prerequisites[edit | edit source]

To follow the instructions in this guide the following programs should be installed first:

1. Visual Studio 2013
2. CMake
3. GIT
4. MinGW with GIT
5. Doxygen (optional)
6. Python (optional)

Preparations[edit | edit source]

1) Launch MinGW as administrator:
WIN > C:\MinGW\msys\1.0\msys.bat Ctrl+Shift+Enter > Alt+y

2) MinGW with GIT
Download MinGW:
http://sourceforge.net/projects/mingw/files/
> http://sourceforge.net/projects/mingw/files/latest/download?source=files

Add GIT to MinGW
Edit C:\MinGW\msys\1.0\etc\profile
export PATH=$PATH:/c/Program\ Files\ \(x86\)/Git/bin

Create alias:
Edit C:\MinGW\msys\1.0\home\home\.profile
alias subl='C:/Program\ Files/Sublime\ Text\ 3/sublime_text.exe'
alias cmake-gui='C:/Program\ Files\ \(x86\)/CMake\ 2.8/bin/cmake-gui.exe'

3) Mercurial
http://mercurial.selenic.com/wiki/Download
http://bitbucket.org/tortoisehg/files/downloads/tortoisehg-2.11.2-hg-2.9.2-x64.msi

GLFW[edit | edit source]

GLFW: Retrieve the source[edit | edit source]

# First time only: clone from GitHub
cd C:/dev/remotes; git clone https://github.com/glfw/glfw.git
# Update the source
rm -rf c:/dev/vsprojects/glfw
cd C:/dev/remotes/glfw; git pull origin master; wait; cp -r . c:/dev/vsprojects/glfw

GLFW: Run CMake (Build VS Project)[edit | edit source]

cd c:/dev/vsprojects/glfw
cmake -G"Visual Studio 12 Win64" --build .

GLFW: Compile from Mingw[edit | edit source]

python
import os
os.system('"C:/Program Files (x86)/MSBuild/12.0/Bin/amd64/MSBuild.exe"\
 /P:Configuration=Release INSTALL.vcxproj')
exit()

GLFW: Copy include and lib files[edit | edit source]

rm -rf c:/dev/bin/glfw.bin.WIN64
mkdir c:/dev/bin/glfw.bin.WIN64
cp -r c:/dev/vsprojects/glfw/include c:/dev/bin/glfw.bin.WIN64
cp -r c:/dev/vsprojects/glfw/src/Release c:/dev/bin/glfw.bin.WIN64/lib

GLFW: Back in Visual Studio[edit | edit source]

Ctrl+Shift+n (FILE > New Project > Win32 Console Application)
Alt+n (Name) test_glfw
Alt+l (Location) c:\dev\tests\glfw
Next > Console Application, Empty Project > Finish
Ctrl+Shift+a (Right Click on HelloWorld project, Add > New Item...), C++ File
Alt+n (Name) hello.cpp > Save
Tutorials#Hello.cpp
Ctrl+S (Save)
Alt+F7 (Select PROJECT > HelloWorld Properties…)
Alt+c r (Configuration: Release)
Configuration Manager
Alt+c r (Active solution configuration: Release)
Alt+p DOWN ENTER DOWN DOWN ENTER (Active solution platform: New, x64)
ENTER (Close)
C/C++ > General > Additional Include Directories:
 C:\dev\bin\glfw.bin.WIN64\include
Linker > General > Additional Library Directories:
 C:\dev\bin\glfw.bin.WIN64\lib
Linker > Input > Additional Dependencies:
 glfw3.lib;opengl32.lib;glu32.lib;
Alt+a (Apply), ENTER (OK)
OK
F7 (Build)

# Run the test application:
cd c:dev/tests/glfw/test_glfw/x64/Release
test_glfw.exe

Zlib[edit | edit source]

Zlib: Retrieve the source[edit | edit source]

# First time only: clone from GitHub
cd c:/dev/remotes; git clone https://github.com/madler/zlib.git
# Update the source
rm -rf c:/dev/vsprojects/zlib
cd c:/dev/remotes/zlib; git pull origin master; wait; cp -r . C:/dev/vsprojects/zlib

Zlib: Run CMake (Build VS Project)[edit | edit source]

cd c:/dev/vsprojects/glfw
cmake -G"Visual Studio 12 Win64" --build .

Zlib: Compile from Mingw[edit | edit source]

python
import os
os.system('"C:/Program Files (x86)/MSBuild/12.0/Bin/amd64/MSBuild.exe"\
 /P:Configuration=Release INSTALL.vcxproj')
exit()

Zlib: Copy include and lib files[edit | edit source]

rm -rf c:/dev/bin/zlib.bin.WIN64
mkdir c:/dev/bin/zlib.bin.WIN64
mkdir c:/dev/bin/zlib.bin.WIN64/include
cp c:/dev/vsprojects/zlib/*.h c:/dev/bin/zlib.bin.WIN64/include
cp -r c:/dev/vsprojects/zlib/Release c:/dev/bin/zlib.bin.WIN64/lib

Zlib: Back in Visual Studio[edit | edit source]

Ctrl+Shift+n (FILE > New Project > Win32 Console Application)
Alt+n (Name) test_zlib
Alt+l (Location) C:\dev\tests\zlib
OK
Next > Console Application, Empty Project > Finish
Ctrl+Shift+a (Right Click on project, Add > New Item...), C++ File
Alt+n (Name) zpipe.cpp ENTER (Add)
Copy paste: Tutorials#zpipe.c
Ctrl+s (Save)
Alt+F7 (Select PROJECT > zpipe Properties…)
Alt+c r (Configuration: Release)
Configuration Manager
Alt+c r (Active solution configuration: Release)
Alt+p DOWN ENTER DOWN DOWN ENTER (Active solution platform: New, x64)
ENTER (Close)
C/C++ > General > Additional Include Directories:
 C:\dev\bin\zlib.bin.WIN64\include
Linker > General > Additional Library Directories:
 C:\dev\bin\zlib.bin.WIN64\lib
Linker > Input > Additional Dependencies:
 zlib.lib;
Alt+a (Apply), ENTER (OK)
OK
F7 (Build)
Alt+f c (Close Project)
Alt+F4 (Close Visual Studio)
# Test zpipe
cd c:/dev/tests/zlib/test_zlib/x64/Release
cp c:/dev/bin/zlib.bin.WIN64/lib/zlib.dll .
cp c:/dev/tests/zlib/test_zlib/test_zlib/zpipe.cpp .
mv test_zlib.exe zpipe.exe
zpipe < zpipe.cpp > zpipe.z
zpipe -d < zpipe.z > zpipe.txt
diff zpipe.cpp zpipe.txt

Libpng[edit | edit source]

http://libpng.org

http://libpng.org/pub/png/libpng.html

Libpng: Retrieve the source[edit | edit source]

# First time only: cd C:/dev/remotes; git clone git://git.code.sf.net/p/libpng/code libpng
rm -rf c:/dev/vsprojects/libpng
cd C:/dev/remotes/libpng; git pull origin master; wait; cp -r . C:/dev/vsprojects/libpng

Libpng: Add external library: zlib[edit | edit source]

# Copy zlib bins to lpng
cd c:/dev/vsprojects/libpng; mkdir external
cp -r c:/dev/bin/zlib.bin.WIN64 external

Libpng: Modify CMakeLists.txt[edit | edit source]

printf "if(COMMAND cmake_policy)\n\
  cmake_policy(SET CMP0003 NEW)\n\
endif(COMMAND cmake_policy)\n\
set(ZLIB_INCLUDE_DIR external/zlib.bin.WIN64/include)\n\
set(ZLIB_LIBRARY external/zlib.bin.WIN64/lib/zlib)\n\
\n\
" > temp.txt
csplit CMakeLists.txt "/project(libpng C)/"
cat xx00 temp.txt xx01 > CMakeLists.txt
rm xx00; rm xx01; rm temp.txt

Libpng: Run CMake (Build VS Project)[edit | edit source]

cmake -G"Visual Studio 12 Win64" --build .

Libpng: Compile from Mingw[edit | edit source]

python
import os
os.system('"C:/Program Files (x86)/MSBuild/12.0/Bin/amd64/MSBuild.exe"\
 /P:Configuration=Release INSTALL.vcxproj')
exit()

Libpng: Run companion applications[edit | edit source]

# To run included testapps, copy dynamic zlib library:
cp C:/dev/bin/zlib.bin.WIN64/lib/zlib.dll C:/dev/vsprojects/libpng/Release
cp c:/dev/resources/libpng/pngtest.png c:/dev/vsprojects/libpng/Release/pngtest.png
cd C:/dev/vsprojects/libpng/Release
pngstest #todo: check what this does
pngtest
pngvalid

Libpng: Copy include and lib files[edit | edit source]

rm -rf c:/dev/bin/libpng.bin.WIN64
mkdir c:/dev/bin/libpng.bin.WIN64
mkdir c:/dev/bin/libpng.bin.WIN64/include
mkdir c:/dev/bin/libpng.bin.WIN64/lib
cp c:/dev/vsprojects/libpng/*.h c:/dev/bin/libpng.bin.WIN64/include
cp c:/dev/vsprojects/libpng/Release/* c:/dev/bin/libpng.bin.WIN64/lib

Libpng: Back in Visual Studio (Test)[edit | edit source]

Ctrl+Shift+n (FILE > New Project > Win32 Console Application)
Alt+n (Name) test_libpng
Alt+l (Location) C:\dev\tests\libpng
OK
Next > Console Application, Empty Project > Finish

Ctrl+Shift+a (Right Click on project, Add > New Item...), C++ File
Alt+n (Name) pngtest.cpp ENTER (Add)
Copy-paste: Tutorials#pngtest.cpp
Ctrl+s (Save)
Alt+F7 (Select PROJECT > pngtest Properties…)
Alt+c r (Configuration: Release)
Configuration Manager
Alt+c r (Active solution configuration: Release)
Alt+p DOWN ENTER DOWN DOWN ENTER (Active solution platform: New, x64)
ENTER (Close)
C/C++ > General > Additional Include Directories:
 C:\dev\bin\libpng.bin.WIN64\include
Linker > General > Additional Library Directories:
 C:\dev\bin\libpng.bin.WIN64\lib
Linker > Input > Additional Dependencies:
 libpng16.lib;
Alt+a (Apply), ENTER (OK)
OK
F7 (Build)
Alt+f t (Close Solution)
Alt+F4 (Close Visual Studio)

<pre>
# Test pngtest
cd c:/dev/tests/libpng/test_libpng/x64/Release
cp c:/dev/resources/libpng/pngfish.png .
cp c:/dev/bin/libpng.bin.WIN64/lib/libpng16.dll .
cp c:/dev/bin/zlib.bin.WIN64/lib/zlib.dll .
mv test_libpng.exe pngfilter.exe
pngfilter pngfish.png outfish.png > output.txt
python
import os; os.system('mspaint outfish.png'); os.system('mspaint pngfish.png')

[Alt+f+x]
[Alt+f+x]
exit()

Libzip[edit | edit source]

http://www.nih.at/libzip/

Libzip: Retrieve the source[edit | edit source]

# (WIN > C:\MinGW\msys\1.0\msys.bat Ctrl+Shift+Enter > Alt+y)
# First time only cd c:/dev/remotes; hg clone http://hg.nih.at/libzip
rm -rf c:/dev/vsprojects/libzip
cd c:/dev/remotes/libzip; hg pull http://hg.nih.at/libzip; wait; hg update
cp -r . C:/dev/vsprojects/libzip

Libzip: Add external library: zlib[edit | edit source]

# Copy zlib bins to libzip
cd c:/dev/vsprojects/libzip; mkdir external; cp -r C:/dev/bin/zlib.bin.WIN64 external

Libzip: Modify CMakeLists.txt[edit | edit source]

printf "if(COMMAND cmake_policy)\n\
  cmake_policy(SET CMP0003 NEW)\n\
endif(COMMAND cmake_policy)\n\
set(ZLIB_INCLUDE_DIR external/zlib.bin.WIN64/include)\n\
set(ZLIB_LIBRARY c:/dev/libzip/external/zlib.bin.WIN64/lib/zlib.lib)\n\
set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)\n\
\n\
" > temp.txt
csplit CMakeLists.txt "/PROJECT(libzip C)/"
cat xx00 temp.txt xx01 > CMakeLists.txt
rm xx00; rm xx01; rm temp.txt
# Quick fix for incorrect version check. Improved fix in stackoverflow.
# http://stackoverflow.com/questions/10507893/libzip-with-visual-studio-2010
# Also contains interesting info on how to use Visual Studio cmd prompt
sed -i 's/FATAL_ERROR/WARNING/' CMakeLists.txt

Libzip: Run CMake (Build VS Project)[edit | edit source]

cmake -G"Visual Studio 12 Win64" --build .

Libzip: Compile from Mingw[edit | edit source]

python
import os
os.system('"C:/Program Files (x86)/MSBuild/12.0/Bin/amd64/MSBuild.exe"\
 /P:Configuration=Release INSTALL.vcxproj')
exit()

Libzip: Copy include and lib files[edit | edit source]

rm -rf c:/dev/bin/libzip.bin.WIN64
mkdir c:/dev/bin/libzip.bin.WIN64
mkdir c:/dev/bin/libzip.bin.WIN64/include
mkdir c:/dev/bin/libzip.bin.WIN64/lib
cp *.h c:/dev/bin/libzip.bin.WIN64/include
cp lib/*.h c:/dev/bin/libzip.bin.WIN64/include
cp lib/Release/* c:/dev/bin/libzip.bin.WIN64/lib

Libzip: Back in Visual Studio (Test)[edit | edit source]

Ctrl+Shift+n (FILE > New Project > Win32 Console Application)
Alt+n (Name) test_libzip
Alt+l (Location) C:\dev\tests\test_libzip
OK
Next > Console Application, Empty Project > Finish
Ctrl+Shift+a (Right Click on project, Add > New Item...), C++ File
Alt+n (Name) libziptest.cpp .cpp ENTER (Add)
Copy-paste: Tutorials#libziptest.cpp
Ctrl+s (Save)
Alt+F7 (Select PROJECT > libziptest Properties…)
Alt+c r (Configuration: Release)
Configuration Manager
Alt+c r (Active solution configuration: Release)
Alt+p DOWN ENTER DOWN DOWN ENTER (Active solution platform: New, x64)
ENTER (Close)
C/C++ > General > Additional Include Directories:
  C:\dev\bin\libzip.bin.WIN64\include
Linker > General > Additional Library Directories:
  C:\dev\bin\libzip.bin.WIN64\lib
Linker > Input > Additional Dependencies:
  zip.lib;
Alt+a (Apply), ENTER (OK)
OK
F7 (Build)
Alt+f+t (Close Solution)
Alt+F4 (Close Visual Studio)

# Test pngtest

cd C:/dev/tests/libzip/test_libzip/x64/Release
echo "HelloWorld" > file.txt
# todo add 7z to path
C:/Program\ Files/7-Zip/7z a -tzip foo.zip file.txt
cp C:/dev/bin/zlib.bin.WIN64/lib/zlib.dll .
cp C:/dev/bin/libzip.bin.WIN64/lib/zip.dll .
mv test_libzip.exe libziptest.exe
libziptest

Links[edit | edit source]

http://www.opengl-tutorial.org/beginners-tutorials/tutorial-1-opening-a-window/

Hello.cpp[edit | edit source]

// http://www.glfw.org/documentation.html#example_code
#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

zpipe.c[edit | edit source]

// http://www.zlib.net/zpipe.c
// Ctrl+h Replace setmode to _setmode and fileno to _fileno
// ESC (Close find replace)
/* zpipe.c: example of proper use of zlib's inflate() and deflate()
   Not copyrighted -- provided to the public domain
   Version 1.4  11 December 2005  Mark Adler */

/* Version history:
   1.0  30 Oct 2004  First version
   1.1   8 Nov 2004  Add void casting for unused return values
                     Use switch statement for inflate() return values
   1.2   9 Nov 2004  Add assertions to document zlib guarantees
   1.3   6 Apr 2005  Remove incorrect assertion in inf()
   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
                     Avoid some compiler warnings for input and output buffers
 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zlib.h"

#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
#  include <fcntl.h>
#  include <io.h>
#  define SET_BINARY_MODE(file) _setmode(_fileno(file), O_BINARY)
#else
#  define SET_BINARY_MODE(file)
#endif

#define CHUNK 16384

/* Compress from file source to file dest until EOF on source.
   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_STREAM_ERROR if an invalid compression
   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
   version of the library linked do not match, or Z_ERRNO if there is
   an error reading or writing the files. */
int def(FILE *source, FILE *dest, int level)
{
    int ret, flush;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit(&strm, level);
    if (ret != Z_OK)
        return ret;

    /* compress until end of file */
    do {
        strm.avail_in = fread(in, 1, CHUNK, source);
        if (ferror(source)) {
            (void)deflateEnd(&strm);
            return Z_ERRNO;
        }
        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
        strm.next_in = in;

        /* run deflate() on input until output buffer not full, finish
           compression if all of source has been read in */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = deflate(&strm, flush);    /* no bad return value */
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            have = CHUNK - strm.avail_out;
            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
                (void)deflateEnd(&strm);
                return Z_ERRNO;
            }
        } while (strm.avail_out == 0);
        assert(strm.avail_in == 0);     /* all input will be used */

        /* done when last data in file processed */
    } while (flush != Z_FINISH);
    assert(ret == Z_STREAM_END);        /* stream will be complete */

    /* clean up and return */
    (void)deflateEnd(&strm);
    return Z_OK;
}

/* Decompress from file source to file dest until stream ends or EOF.
   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_DATA_ERROR if the deflate data is
   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
   the version of the library linked do not match, or Z_ERRNO if there
   is an error reading or writing the files. */
int inf(FILE *source, FILE *dest)
{
    int ret;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    do {
        strm.avail_in = fread(in, 1, CHUNK, source);
        if (ferror(source)) {
            (void)inflateEnd(&strm);
            return Z_ERRNO;
        }
        if (strm.avail_in == 0)
            break;
        strm.next_in = in;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }
            have = CHUNK - strm.avail_out;
            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
                (void)inflateEnd(&strm);
                return Z_ERRNO;
            }
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    /* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

/* report a zlib or i/o error */
void zerr(int ret)
{
    fputs("zpipe: ", stderr);
    switch (ret) {
    case Z_ERRNO:
        if (ferror(stdin))
            fputs("error reading stdin\n", stderr);
        if (ferror(stdout))
            fputs("error writing stdout\n", stderr);
        break;
    case Z_STREAM_ERROR:
        fputs("invalid compression level\n", stderr);
        break;
    case Z_DATA_ERROR:
        fputs("invalid or incomplete deflate data\n", stderr);
        break;
    case Z_MEM_ERROR:
        fputs("out of memory\n", stderr);
        break;
    case Z_VERSION_ERROR:
        fputs("zlib version mismatch!\n", stderr);
    }
}

/* compress or decompress from stdin to stdout */
int main(int argc, char **argv)
{
    int ret;

    /* avoid end-of-line conversions */
    SET_BINARY_MODE(stdin);
    SET_BINARY_MODE(stdout);

    /* do compression if no arguments */
    if (argc == 1) {
        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
        if (ret != Z_OK)
            zerr(ret);
        return ret;
    }

    /* do decompression if -d specified */
    else if (argc == 2 && strcmp(argv[1], "-d") == 0) {
        ret = inf(stdin, stdout);
        if (ret != Z_OK)
            zerr(ret);
        return ret;
    }

    /* otherwise, report usage */
    else {
        fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr);
        return 1;
    }
}

pngtest.cpp[edit | edit source]

/* Copy example from http://zarb.org/~gc/resource/libpng-short-example.c
   Modify source:
   Ctrl+h <unistd> TAB <io.h> ENTER ENTER ESC (Close find replace)
   TOP #define _CRT_SECURE_NO_WARNINGS
   Comment all blocks containing setjmp, png_set_strip_16, png_set_expand
   // Move [*]/ in /[*] perform whatever ... [*]/ to the end of the top line
*/
/*
 * Copyright 2002-2011 Guillaume Cottenceau and contributors.
 *
 * This software may be freely redistributed under the terms
 * of the X11 license.
 *
 */

#define _CRT_SECURE_NO_WARNINGS
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#define PNG_DEBUG 3
#include <png.h>

void abort_(const char * s, ...)
{
    va_list args;
    va_start(args, s);
    vfprintf(stderr, s, args);
    fprintf(stderr, "\n");
    va_end(args);
    abort();
}

int x, y;

int width, height, rowbytes;
png_byte color_type;
png_byte bit_depth;

png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers;

void read_png_file(char* file_name)
{
    unsigned char header[8];    // 8 is the maximum size that can be checked

    /* open file and test for it being a png */
    FILE *fp = fopen(file_name, "rb");
    if (!fp)
        abort_("[read_png_file] File %s could not be opened for reading", file_name);
    fread(header, 1, 8, fp);
    if (png_sig_cmp(header, 0, 8))
        abort_("[read_png_file] File %s is not recognized as a PNG file", file_name);


    /* initialize stuff */
    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!png_ptr)
        abort_("[read_png_file] png_create_read_struct failed");

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
        abort_("[read_png_file] png_create_info_struct failed");
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[read_png_file] Error during init_io");
        */
    png_init_io(png_ptr, fp);
    png_set_sig_bytes(png_ptr, 8);

    png_read_info(png_ptr, info_ptr);

    width = png_get_image_width(png_ptr, info_ptr);
    height = png_get_image_height(png_ptr, info_ptr);
    color_type = png_get_color_type(png_ptr, info_ptr);
    bit_depth = png_get_bit_depth(png_ptr, info_ptr);

    number_of_passes = png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);


    /* read file */
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[read_png_file] Error during read_image");
        */
    row_pointers = (png_bytep*)malloc(sizeof(png_bytep)* height);

    if (bit_depth == 16)
        rowbytes = width * 8;
    else
        rowbytes = width * 4;

    for (y = 0; y<height; y++)
        row_pointers[y] = (png_byte*)malloc(rowbytes);

    png_read_image(png_ptr, row_pointers);

    fclose(fp);
}


void write_png_file(char* file_name)
{
    /* create file */
    FILE *fp = fopen(file_name, "wb");
    if (!fp)
        abort_("[write_png_file] File %s could not be opened for writing", file_name);


    /* initialize stuff */
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!png_ptr)
        abort_("[write_png_file] png_create_write_struct failed");

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
        abort_("[write_png_file] png_create_info_struct failed");
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[write_png_file] Error during init_io");
        */
    png_init_io(png_ptr, fp);


    /* write header */
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[write_png_file] Error during writing header");
        */
    png_set_IHDR(png_ptr, info_ptr, width, height,
        8, 6, PNG_INTERLACE_NONE,
        PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

    png_write_info(png_ptr, info_ptr);


    /* write bytes */
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[write_png_file] Error during writing bytes");
        */
    png_write_image(png_ptr, row_pointers);


    /* end write */
    /*
    if (setjmp(png_jmpbuf(png_ptr)))
        abort_("[write_png_file] Error during end of write");
        */
    png_write_end(png_ptr, NULL);

    /* cleanup heap allocation */
    for (y = 0; y<height; y++)
        free(row_pointers[y]);
    free(row_pointers);

    fclose(fp);
}


void process_file(void)
{
    /* Expand any grayscale, RGB, or palette images to RGBA */
    //png_set_expand(png_ptr);

    /* Reduce any 16-bits-per-sample images to 8-bits-per-sample */
    //png_set_strip_16(png_ptr);

    for (y = 0; y<height; y++) {
        png_byte* row = row_pointers[y];
        for (x = 0; x<width; x++) {
            png_byte* ptr = &(row[x * 4]);
            printf("Pixel at position [ %d - %d ] has RGBA values: %d - %d - %d - %d\n",
                x, y, ptr[0], ptr[1], ptr[2], ptr[3]);

            /* perform whatever modifications needed, for example to set red value to 0 and green value to the blue one: */
            ptr[0] = 0;
            ptr[1] = ptr[2];
        }
    }
}


int main(int argc, char **argv)
{
    if (argc != 3)
        abort_("Usage: program_name <file_in> <file_out>");

    read_png_file(argv[1]);
    process_file();
    write_png_file(argv[2]);

    return 0;
}

libziptest.cpp[edit | edit source]

// Source
// http://stackoverflow.com/questions/10440113/simple-way-to-unzip-a-zip-file-using-zlib
#include <zip.h>

int main()
{
  //Open the ZIP archive
  int err = 0;
  zip *z = zip_open("foo.zip", 0, &err);

  //Search for the file of given name
  const char *name = "file.txt";
  struct zip_stat st;
  zip_stat_init(&st);
  zip_stat(z, name, 0, &st);

  //Alloc memory for its uncompressed contents
  char *contents = new char[st.size];

  //Read the compressed file
  zip_file *f = zip_fopen(z, "file.txt", 0);
  zip_fread(f, contents, st.size);
  zip_fclose(f);

  //And close the archive
  zip_close(z);

  printf("contents:\n%s", contents);
}