Guest User

Untitled

a guest
Jun 17th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.70 KB | None | 0 0
  1. //---------------------------------------------------------------------------
  2.  
  3. #include <vcl.h>
  4. #include <vector>
  5. #include <stdio>
  6. #include <algorithm>
  7. #pragma hdrstop
  8.  
  9. #include "Unit1.h"
  10. //---------------------------------------------------------------------------
  11. #pragma package(smart_init)
  12. #pragma resource "*.dfm"
  13. TForm1 *Form1;
  14.  
  15. struct DISPL { float x;
  16. float y;}; //разрешение гориз и верт
  17.  
  18. struct NOTEBOOK {
  19. char model[21]; // наименование-модель
  20. DISPL r;
  21. int f; //частота регенерации
  22. int tf; //тактовая частота процессора
  23. float d; //размер диагонали дисплея
  24. float vm; //объём видеопамяти
  25. float hdd; //объём диска
  26. int price; }; //цена
  27.  
  28. std::vector<NOTEBOOK> si; // данные о всех ноутах
  29. long howmuch=0; // количество записей в файле
  30.  
  31. FILE *myfile; // указатель на файл с бинарными данными о буках
  32.  
  33. bool saveToFile(std::vector<NOTEBOOK>);
  34. void createNewElement();
  35. bool readScanInfo();
  36. void vsort(std::vector<NOTEBOOK>);
  37.  
  38. //---------------------------------------------------------------------------
  39. __fastcall TForm1::TForm1(TComponent* Owner)
  40. : TForm(Owner)
  41. {
  42. if (!readScanInfo())
  43. ShowMessage("Файл данных отсутствует или поврежден, загрузка данных невозможна. [error:0]\nФайл будет воссоздан автоматически при добавлении нового элемента.");
  44.  
  45. for (unsigned int i = 0; i < si.size(); i++)
  46. ListBox1->Items->Add((AnsiString) si[i].model);
  47.  
  48. }
  49. //---------------------------------------------------------------------------
  50.  
  51. void __fastcall TForm1::Button1Click(TObject *Sender)
  52. {
  53. //открываем наш файлик
  54. if (OpenDialog1->Execute())
  55. Memo1->Lines->LoadFromFile(OpenDialog1->FileName);
  56. }
  57. /**
  58. * Чтение структур из файла
  59. * @return bool true если удалось прочесть файл, false если файла не существует или нехватает прав
  60. **/
  61. bool readScanInfo()
  62. {
  63. myfile = fopen("scaninfo.dat","rb"); // read only, binary
  64. if (myfile)
  65. {
  66. //fseek(myfile, 0, SEEK_SET); // pointer to start
  67. fread(&howmuch, sizeof(long), 1, myfile); // get items count
  68.  
  69. //si.clear(); //vect
  70. si.resize(howmuch); //vect
  71. //fseek(myfile, 4, SEEK_SET);
  72. //ShowMessage("hi: " + (AnsiString)sizeof(long));
  73. fread(&si[0], sizeof(NOTEBOOK)/*24*/, howmuch, myfile); // read ScanInfo's
  74. // по условию требуется, чтобы howmuch было long, поэтому делаем лишний cast
  75.  
  76. return true;
  77. }
  78. else
  79. {
  80. return false;
  81. }
  82. }
  83.  
  84. /**
  85. * Соханение информации о сканерах в бинарный файл <*.dat>
  86. * @return true в случае успешного сохранение, false при провале
  87. */
  88. bool saveToFile(std::vector<NOTEBOOK> si)
  89. {
  90. long items; // количество записей в файле
  91. myfile = fopen("scaninfo.dat","wb+"); // create/clean, read+write, binary
  92. if (myfile)
  93. {
  94. fwrite(&howmuch, sizeof(long), 1, myfile); // обновляем кол-во записей в файле
  95. fwrite(&si[0], sizeof(NOTEBOOK), si.size(), myfile); // дамп всех данных
  96. fclose(myfile);
  97. return true;
  98. }
  99. else
  100. {
  101. ShowMessage("Невозможно открыть файл [error:1]");
  102. return false;
  103. }
  104. }
  105.  
  106. bool NOTEBOOK::operator < (const NOTEBOOK &Other) const
  107. {
  108. int result = strcmp(model, Other.model);
  109.  
  110. if (result < 0)
  111. return true;
  112. else
  113. return false;
  114. }
  115.  
  116. //---------------------------------------------------------------------------
  117. // Кнопка удаления --
  118. void __fastcall TForm1::Button2Click(TObject *Sender)
  119. {
  120. if (ListBox1->ItemIndex != -1)
  121. {
  122. si.erase(si.begin() + ListBox1->ItemIndex); // удаляем элемент из памяти
  123. howmuch--;
  124. saveToFile(si); // сразу сохраняем укороченный список в файл
  125. ListBox1->Items->Delete(ListBox1->ItemIndex); // вместо полного обновления удаляем строку из списка
  126.  
  127. // очищаем поля
  128. Edit1->Text = "";
  129. Edit2->Text = "";
  130. Edit3->Text = "";
  131. Edit4->Text = "";
  132. Edit5->Text = "";
  133. Edit6->Text = "";
  134. Edit7->Text = "";
  135. Edit8->Text = "";
  136. Edit9->Text = "";
  137. }
  138. }
  139. //---------------------------------------------------------------------------
  140. //кнопка добавления
  141. void __fastcall TForm1::Button3Click(TObject *Sender)
  142. {
  143. if (Edit1->Text != ""
  144. && Edit2->Text != ""
  145. && Edit3->Text != ""
  146. && Edit4->Text != ""
  147. && Edit5->Text != ""
  148. && Edit6->Text != ""
  149. && Edit7->Text != ""
  150. && Edit8->Text != ""
  151. && Edit9->Text != "")
  152. {
  153. strcpy(sample.model, Edit8->Text.c_str());
  154. sample.price = Edit9->Text.ToInt();
  155. sample.x = Edit1->Text.ToFloat();
  156. sample.y = Edit2->Text.ToFloat();
  157. sample.f = Edit3->Text.ToInt();
  158. sample.tf = Edit4->Text.ToInt();
  159. sample.d = Edit5->Text.ToFloat();
  160. sample.hdd = Edit7->Text.ToFloat();
  161.  
  162. si.push_back(sample);
  163. howmuch++;
  164. saveToFile(si);
  165. ListBox1->Items->Add(Edit8->Text);
  166.  
  167. // очищаем поля
  168. Edit1->Text = "";
  169. Edit2->Text = "";
  170. Edit3->Text = "";
  171. Edit4->Text = "";
  172. Edit5->Text = "";
  173. Edit6->Text = "";
  174. Edit7->Text = "";
  175. Edit8->Text = "";
  176. Edit9->Text = "";
  177. }
  178. }
  179.  
  180. //---------------------------------------------------------------------------
  181.  
  182. void __fastcall TForm1::ListBox1Click(TObject *Sender)
  183. {
  184. if (ListBox1->ItemIndex != -1)
  185. {
  186. Edit8->Text = si[ListBox1->ItemIndex].model;
  187. Edit9->Text = si[ListBox1->ItemIndex].price;
  188. Edit1->Text = si[ListBox1->ItemIndex].x;
  189. Edit2->Text = si[ListBox1->ItemIndex].y;
  190. Edit3->Text = si[ListBox1->ItemIndex].f;
  191. Edit4->Text = si[ListBox1->ItemIndex].tf;
  192. Edit5->Text = si[ListBox1->ItemIndex].d;
  193. Edit6->Text = si[ListBox1->ItemIndex].vm;
  194. Edit7->Text = si[ListBox1->ItemIndex].hdd;
  195. }
  196. }
  197. //---------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment