Загрузка данных


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *title;
    char *author;
    int year;
} Book;

void book_init(Book *b, const char *title,
               const char *author, int year)
{
    b->title = strdup(title);
    b->author = strdup(author);
    b->year = year;
}

void book_destroy(Book *b)
{
    free(b->title);
    free(b->author);
}

void print_book(const Book *b)
{
    printf("\"%s\" by %s (%d)\n",
           b->title,
           b->author,
           b->year);
}

int cmp_by_year(const void *a, const void *b)
{
    return ((Book *)a)->year - ((Book *)b)->year;
}

int main()
{
    int count = 3;

    Book *library = malloc(count * sizeof(Book));

    book_init(&library[0],
              "The C++ Programming Language",
              "Bjarne Stroustrup",
              2013);

    book_init(&library[1],
              "Effective Modern C++",
              "Scott Meyers",
              2014);

    book_init(&library[2],
              "The Art of Computer Programming",
              "Donald Knuth",
              1968);

    printf("Before sorting:\n");

    for (int i = 0; i < count; i++)
        print_book(&library[i]);

    qsort(library,
          count,
          sizeof(Book),
          cmp_by_year);

    printf("\nSorted by year:\n");

    for (int i = 0; i < count; i++)
        print_book(&library[i]);

    for (int i = 0; i < count; i++)
        book_destroy(&library[i]);

    free(library);

    return 0;
}