Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #include <vector>
- #include <stdio>
- #include <algorithm>
- #pragma hdrstop
- #include "Unit1.h"
- //---------------------------------------------------------------------------
- #pragma package(smart_init)
- #pragma resource "*.dfm"
- TForm1 *Form1;
- struct DISPL { float x;
- float y;}; //разрешение гориз и верт
- struct NOTEBOOK {
- char model[21]; // наименование-модель
- DISPL r;
- int f; //частота регенерации
- int tf; //тактовая частота процессора
- float d; //размер диагонали дисплея
- float vm; //объём видеопамяти
- float hdd; //объём диска
- int price; }; //цена
- std::vector<NOTEBOOK> si; // данные о всех ноутах
- long howmuch=0; // количество записей в файле
- FILE *myfile; // указатель на файл с бинарными данными о буках
- bool saveToFile(std::vector<NOTEBOOK>);
- void createNewElement();
- bool readScanInfo();
- void vsort(std::vector<NOTEBOOK>);
- //---------------------------------------------------------------------------
- __fastcall TForm1::TForm1(TComponent* Owner)
- : TForm(Owner)
- {
- if (!readScanInfo())
- ShowMessage("Файл данных отсутствует или поврежден, загрузка данных невозможна. [error:0]\nФайл будет воссоздан автоматически при добавлении нового элемента.");
- for (unsigned int i = 0; i < si.size(); i++)
- ListBox1->Items->Add((AnsiString) si[i].model);
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Button1Click(TObject *Sender)
- {
- //открываем наш файлик
- if (OpenDialog1->Execute())
- Memo1->Lines->LoadFromFile(OpenDialog1->FileName);
- }
- /**
- * Чтение структур из файла
- * @return bool true если удалось прочесть файл, false если файла не существует или нехватает прав
- **/
- bool readScanInfo()
- {
- myfile = fopen("scaninfo.dat","rb"); // read only, binary
- if (myfile)
- {
- //fseek(myfile, 0, SEEK_SET); // pointer to start
- fread(&howmuch, sizeof(long), 1, myfile); // get items count
- //si.clear(); //vect
- si.resize(howmuch); //vect
- //fseek(myfile, 4, SEEK_SET);
- //ShowMessage("hi: " + (AnsiString)sizeof(long));
- fread(&si[0], sizeof(NOTEBOOK)/*24*/, howmuch, myfile); // read ScanInfo's
- // по условию требуется, чтобы howmuch было long, поэтому делаем лишний cast
- return true;
- }
- else
- {
- return false;
- }
- }
- /**
- * Соханение информации о сканерах в бинарный файл <*.dat>
- * @return true в случае успешного сохранение, false при провале
- */
- bool saveToFile(std::vector<NOTEBOOK> si)
- {
- long items; // количество записей в файле
- myfile = fopen("scaninfo.dat","wb+"); // create/clean, read+write, binary
- if (myfile)
- {
- fwrite(&howmuch, sizeof(long), 1, myfile); // обновляем кол-во записей в файле
- fwrite(&si[0], sizeof(NOTEBOOK), si.size(), myfile); // дамп всех данных
- fclose(myfile);
- return true;
- }
- else
- {
- ShowMessage("Невозможно открыть файл [error:1]");
- return false;
- }
- }
- bool NOTEBOOK::operator < (const NOTEBOOK &Other) const
- {
- int result = strcmp(model, Other.model);
- if (result < 0)
- return true;
- else
- return false;
- }
- //---------------------------------------------------------------------------
- // Кнопка удаления --
- void __fastcall TForm1::Button2Click(TObject *Sender)
- {
- if (ListBox1->ItemIndex != -1)
- {
- si.erase(si.begin() + ListBox1->ItemIndex); // удаляем элемент из памяти
- howmuch--;
- saveToFile(si); // сразу сохраняем укороченный список в файл
- ListBox1->Items->Delete(ListBox1->ItemIndex); // вместо полного обновления удаляем строку из списка
- // очищаем поля
- Edit1->Text = "";
- Edit2->Text = "";
- Edit3->Text = "";
- Edit4->Text = "";
- Edit5->Text = "";
- Edit6->Text = "";
- Edit7->Text = "";
- Edit8->Text = "";
- Edit9->Text = "";
- }
- }
- //---------------------------------------------------------------------------
- //кнопка добавления
- void __fastcall TForm1::Button3Click(TObject *Sender)
- {
- if (Edit1->Text != ""
- && Edit2->Text != ""
- && Edit3->Text != ""
- && Edit4->Text != ""
- && Edit5->Text != ""
- && Edit6->Text != ""
- && Edit7->Text != ""
- && Edit8->Text != ""
- && Edit9->Text != "")
- {
- strcpy(sample.model, Edit8->Text.c_str());
- sample.price = Edit9->Text.ToInt();
- sample.x = Edit1->Text.ToFloat();
- sample.y = Edit2->Text.ToFloat();
- sample.f = Edit3->Text.ToInt();
- sample.tf = Edit4->Text.ToInt();
- sample.d = Edit5->Text.ToFloat();
- sample.hdd = Edit7->Text.ToFloat();
- si.push_back(sample);
- howmuch++;
- saveToFile(si);
- ListBox1->Items->Add(Edit8->Text);
- // очищаем поля
- Edit1->Text = "";
- Edit2->Text = "";
- Edit3->Text = "";
- Edit4->Text = "";
- Edit5->Text = "";
- Edit6->Text = "";
- Edit7->Text = "";
- Edit8->Text = "";
- Edit9->Text = "";
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::ListBox1Click(TObject *Sender)
- {
- if (ListBox1->ItemIndex != -1)
- {
- Edit8->Text = si[ListBox1->ItemIndex].model;
- Edit9->Text = si[ListBox1->ItemIndex].price;
- Edit1->Text = si[ListBox1->ItemIndex].x;
- Edit2->Text = si[ListBox1->ItemIndex].y;
- Edit3->Text = si[ListBox1->ItemIndex].f;
- Edit4->Text = si[ListBox1->ItemIndex].tf;
- Edit5->Text = si[ListBox1->ItemIndex].d;
- Edit6->Text = si[ListBox1->ItemIndex].vm;
- Edit7->Text = si[ListBox1->ItemIndex].hdd;
- }
- }
- //---------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment