Тема: Бінарні файли. Робота с файлами засобами мови С++
Добрий день. Переписати з вхідного файлу у вихідний кожен третій блок.
#include <iostream>
#include <fstream>
using namespace std;
struct Detal_and_garant
{
int element; // тип деталей
char detal[30]; // деталі
char virobnik[30]; // виробник
char model[50]; // модель
double price; // ціна
int mounths;// місяци гарантії
};
int main()
{
setlocale(LC_CTYPE, "ukr");
Detal_and_garant sborka[] = { {1,"Вiдеокарта", "Nvidia", "3070", 20000 , {12}}, {2, "Процессор", "intel", "core i9-12900k", 23000, {24}}, {3, "Матер", "Asus", "prime z590-p", 7500, {8}}, {4, "Блок живлення", "Asus", "750W TUF", 4400, {12}}, {5, "ОЗУ", "KINGSTON", "Beast Black DDR4-3600 16384 MB PC4-28800", 2300, {16}}, {6, "SSD", "KINGSTON", "A400 240GB 2.5", 1000, {12}}, {7, "ЖОРСТКИЙ ДИСК", "SEAGATE", " BarraCuda", 1500, {24}}, {8, "Корпус", "Vision", "Frime Vision White LED", 1500, {8}}, {9, "Кулер", "ID-Cooling", "SE-903-SD", 500, {12}} };
//write array to file
fstream d;
d.open("file.dat", ios::binary | ios::out | ios::trunc);
d.write((char*)sborka, sizeof sborka);
d.close();
//read from file first, fourth and last recordsъх
Detal_and_garant detal_and_garant{};
int size_of_record = sizeof Detal_and_garant;
//cout << "Size of record = (char[8])" << sizeof detal_and_garant.element << " + (char)" << sizeof(char) << " + (char)" << sizeof(char) << " + (char)" << sizeof(char) << " + (double)" << sizeof(double) << " + (int)" << sizeof(int) << " = " << sizeof Detal_and_garant << "\n\n";
d.open("file.dat", ios::binary | ios::in);
// third
d.seekg(2 * size_of_record, ios::beg);
d.read((char*)(&detal_and_garant), size_of_record);
cout << "third detal : (" << detal_and_garant.element << ", Detal - " << detal_and_garant.detal << ", virobnik - " << detal_and_garant.virobnik << ", model - " << detal_and_garant.model << ", price - " << detal_and_garant.price << ", mounth - " << detal_and_garant.mounths << ")\n";
// sixth
d.seekg(5 * size_of_record, ios::beg);
d.read((char*)(&detal_and_garant), size_of_record);
cout << "sixth detal : (" << detal_and_garant.element << ", Detal - " << detal_and_garant.detal << ", virobnik - " << detal_and_garant.virobnik << ", model - " << detal_and_garant.model << ", price - " << detal_and_garant.price << ", mounth - " << detal_and_garant.mounths << ")\n";
// ninth
d.seekg(-size_of_record, ios::end);
d.read((char*)(&detal_and_garant), size_of_record);
cout << "ninth detal : (" << detal_and_garant.element << ", Detal - " << detal_and_garant.detal << ", virobnik - " << detal_and_garant.virobnik << ", model - " << detal_and_garant.model << ", price - " << detal_and_garant.price << ", mounth - " << detal_and_garant.mounths << ")\n";
d.close();
}