این مثال دو بخش دارد، یکی ایجاد پایگاه داده از اطلاعات کتابها و نوشتن آنها در فایل باینری book_data.db و بخش دوم شامل خواندن اطلاعات از همین فایل و نمایش آنها. ویدیوی ضبط شده مربوط به این مثال در پست بعدی منتشر می شود.
#include "stdafx.h" #include <iostream> struct BookInfo { char name[30]; char author[30]; int nPage; float price; int year; }; void CreateDatabase() { printf("To start, enter number of books you want to store in the database\n"); int n = 0; scanf_s("%d", &n); printf("Please enter Book information for %d books as follows\n", n); printf("Name, Author, Pages, Price, Year of Publication\n"); BookInfo *books = new BookInfo[n]; for (int i = 0; i < n; i++) { std::cin.ignore(); printf("\n#%d Name: ", i + 1); gets_s(books[i].name, 30); printf("\n#%d Author: ", i + 1); gets_s(books[i].author, 30); printf("\n#%d Pages: ", i + 1); scanf_s("%d", &books[i].nPage); printf("\n#%d Price: ", i + 1); scanf_s("%f", &books[i].price); printf("\n#%d Year: ", i + 1); scanf_s("%d", &books[i].year); } FILE* fp = 0; fopen_s(&fp, "book_data.db", "wb"); if (!fp) { printf("File can't be oppened.\n"); return; } fwrite(books, sizeof(BookInfo), n, fp); fclose(fp); printf("Data saved successfully\n"); } void ReadDatabase() { int n = 2; BookInfo *books = new BookInfo[n]; FILE* fp = 0; fopen_s(&fp, "book_data.db", "rb"); if (!fp) { printf("File can't be oppened.\n"); return; } fread(books, sizeof(BookInfo), n, fp); for (int i = 0; i < n; i++) { printf("\n#%d Name: %s", i + 1, books[i].name); printf("\n#%d Author: %s", i + 1, books[i].author); printf("\n#%d Pages: %d", i + 1, books[i].nPage); printf("\n#%d Price: %.1f", i + 1, books[i].price); printf("\n#%d Year: %d", i + 1, books[i].year); printf("\n--------------------------------------------"); } fclose(fp); delete[] books; } int main() { printf("Welcome to Book Database Application:\n"); bool create_data = false; //change to false for read mode if (create_data) CreateDatabase(); else ReadDatabase(); getchar(); return 0; }