1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
| unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
StringGrid1: TStringGrid;
SaveDialog1: TSaveDialog;
SaveDialog2: TSaveDialog;
OpenDialog1: TOpenDialog;
OpenDialog2: TOpenDialog;
Edit1: TEdit;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure StringGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Math;
type
TAuto = record
Marka : String[30];
Region : String[30];
Price : Extended;
end;
//Перенос данных из типизированного файла в текстовый файл.
procedure FileType2Txt(Fn1, Fn2 : String);
var
F1 : file of TAuto;
F2 : TextFile;
Auto : TAuto;
Num : Integer;
begin
AssignFile(F1, Fn1);
AssignFile(F2, Fn2);
Reset(F1);
Rewrite(F2);
Num := 0;
while not Eof(F1) do begin
Read(F1, Auto);
Inc(Num);
Writeln(F2, Num:4, ', Автомобиль:');
Writeln(F2, 'Марка: ', Auto.Marka);
Writeln(F2, 'Регион: ', Auto.Region);
Writeln(F2, 'Цена: ' + FloatToStr(Auto.Price) );
Writeln(F2, '--------------------------------------------------');
end;
CloseFile(F1);
CloseFile(F2);
end;
//Сортировка данных типизированного файла.
procedure FileSort(Fn : String);
var
F : file of TAuto;
Arr : array of TAuto;
i, j : Integer;
Auto : TAuto;
begin
AssignFile(F, Fn);
Reset(F);
SetLength(Arr, FileSize(F));
//Загрузка данных из типизированного файла в массив.
i := -1;
while not Eof(F) do begin
Inc(i);
Read(F, Arr[i]);
end;
//Сортировка массива методом вставок.
for i := 0 + 1 to High(Arr) do begin
j := i;
Auto := Arr[i];
while ( j > 0 ) and ( Arr[j - 1].Price > Auto.Price ) do begin
Arr[j] := Arr[j - 1];
Dec(j);
end;
Arr[j] := Auto;
end;
//Выгрузка данных из массива в типизированный файл.
Reset(F); //Либо: Seek(F, 0);
for i := 0 to High(Arr) do begin
Write(F, Arr[i]);
end;
CloseFile(F);
Finalize(Arr);
end;
//Удаление из типизированного файла элемента с номером aNum.
procedure FileDelElem(Fn : String; aNum : Integer);
var
F, FTmp : file of TAuto;
FnTmp : String;
Auto : TAuto;
Num : Integer;
begin
//Имя (полный путь) временного файла.
FnTmp := Fn + '~';
AssignFile(FTmp, Fn);
//Переименовываем исходный файл. Присваимваем ему имя временного файла.
Rename(FTmp, FnTmp);
//Открываем временный (исходный) файл.
Reset(FTmp);
//Создаём новый файл с именем Fn. Этот файл назовём целевым.
AssignFile(F, Fn);
Rewrite(F);
//Переписываем из временного файла в целевой файл все компоненты, кроме
//элемента с номером aNum.
Num := 0;
while not Eof(FTmp) do begin
Inc(Num);
Read(FTmp, Auto);
//Если встретился элемент с номером aNum - пропускаем его.
if Num = aNum then Continue;
Write(F, Auto);
end;
//Закрываем файлы.
CloseFile(F);
CloseFile(FTmp);
//Удаляем временный файл.
Erase(FTmp);
end;
//Проверяет является ли пустой строка с индексом aRow.
function RowIsEmpty(aSg : TStringGrid; aRow : Integer) : Boolean;
var
Col : Integer;
begin
Result := True;
for Col := aSg.FixedCols to aSg.ColCount - 1 do begin
if aSg.Cells[Col, aRow] <> '' then begin
Result := False;
Break;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.Cells[1, 0] := 'Марка';
StringGrid1.Cells[2, 0] := 'Регион';
StringGrid1.Cells[3, 0] := 'Цена';
end;
procedure TForm1.StringGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
Sg : TStringGrid;
begin
Sg := Sender as TStringGrid;
case Key of
//Если уходим с нижней строки вверх, и нижняя строка пустая, то убираем её.
VK_UP :
begin
if
(Sg.Selection.Bottom = Sg.RowCount - 1)
and (Sg.Selection.Bottom <> Sg.FixedRows)
and RowIsEmpty(Sg, Sg.Selection.Bottom)
then begin
Sg.RowCount := Sg.RowCount - 1;
end;
end;
//Если требуется, добавляем новую строку внизу таблицы.
VK_DOWN :
begin
if
(Sg.Selection.Bottom = Sg.RowCount - 1)
and ( not RowIsEmpty(Sg, Sg.Selection.Bottom) )
then begin
Sg.RowCount := Sg.RowCount + 1;
end;
end;
end;
end;
//Записать данные в типизированный файл.
procedure TForm1.Button1Click(Sender: TObject);
var
F : file of TAuto;
Auto : TAuto;
Row, Col : Integer;
begin
if SaveDialog1.InitialDir = '' then begin
SaveDialog1.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not SaveDialog1.Execute then Exit;
AssignFile(F, SaveDialog1.FileName);
Rewrite(F);
Col := StringGrid1.FixedCols;
for Row := StringGrid1.FixedRows to StringGrid1.RowCount - 1 do begin
if RowIsEmpty(StringGrid1, Row) then Continue;
Auto.Marka := StringGrid1.Cells[Col, Row];
Auto.Region := StringGrid1.Cells[Col + 1, Row];
Auto.Price := StrToFloat( StringGrid1.Cells[Col + 2, Row] );
Write(F, Auto);
end;
CloseFile(F);
end;
//Прочитать данные из типизированного файла.
procedure TForm1.Button2Click(Sender: TObject);
var
F : file of TAuto;
Auto : TAuto;
Row, Col : Integer;
begin
OpenDialog1.InitialDir := SaveDialog1.InitialDir;
if OpenDialog1.InitialDir = '' then begin
OpenDialog1.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not OpenDialog1.Execute then Exit;
if not FileExists(OpenDialog1.FileName) then begin
ShowMessage('Файл с указанным именем не найден. Действие отменено.');
Exit;
end;
AssignFile(F, OpenDialog1.FileName);
Reset(F);
Row := StringGrid1.FixedRows - 1;
Col := StringGrid1.FixedCols;
while not Eof(F) do begin
Inc(Row);
if Row = StringGrid1.RowCount then StringGrid1.RowCount := StringGrid1.RowCount + 1;
Read(F, Auto);
StringGrid1.Cells[Col, Row] := Auto.Marka;
StringGrid1.Cells[Col + 1, Row] := Auto.Region;
StringGrid1.Cells[Col + 2, Row] := FloatToStr( RoundTo(Auto.Price, -2) );
end;
StringGrid1.RowCount := Row + 1;
CloseFile(F);
end;
//Сортировать записи типизированного файла по возрастанию цены.
procedure TForm1.Button3Click(Sender: TObject);
begin
OpenDialog1.InitialDir := SaveDialog1.InitialDir;
if OpenDialog1.InitialDir = '' then begin
OpenDialog1.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not OpenDialog1.Execute then Exit;
if not FileExists(OpenDialog1.FileName) then begin
ShowMessage('Файл с указанным именем не найден. Действие отменено.');
Exit;
end;
FileSort(OpenDialog1.FileName);
ShowMessage('Сортировка выполнена.');
end;
//Удалить из типизированного файла элемент с заданным номером.
procedure TForm1.Button4Click(Sender: TObject);
begin
OpenDialog1.InitialDir := SaveDialog1.InitialDir;
if OpenDialog1.InitialDir = '' then begin
OpenDialog1.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not OpenDialog1.Execute then Exit;
if not FileExists(OpenDialog1.FileName) then begin
ShowMessage('Файл с указанным именем не найден. Действие отменено.');
Exit;
end;
FileDelElem( OpenDialog1.FileName, StrToInt(Edit1.Text) );
ShowMessage('Удаление выполнено.');
end;
//Переписать данные из типизированного файла в текстовый файл.
procedure TForm1.Button5Click(Sender: TObject);
begin
OpenDialog1.InitialDir := SaveDialog1.InitialDir;
if OpenDialog1.InitialDir = '' then begin
OpenDialog1.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not OpenDialog1.Execute then Exit;
if not FileExists(OpenDialog1.FileName) then begin
ShowMessage('Файл с указанным именем не найден. Действие отменено.');
Exit;
end;
SaveDialog2.InitialDir := OpenDialog1.InitialDir;
if not SaveDialog2.Execute then Exit;
FileType2Txt(OpenDialog1.FileName, SaveDialog2.FileName);
ShowMessage('Данные переписаны.');
end;
//Прочитать данные из текстового файла.
procedure TForm1.Button6Click(Sender: TObject);
begin
OpenDialog2.InitialDir := SaveDialog2.InitialDir;
if OpenDialog2.InitialDir = '' then begin
OpenDialog2.InitialDir := ExtractFilePath( Application.ExeName );
end;
if not OpenDialog2.Execute then Exit;
if not FileExists(OpenDialog2.FileName) then begin
ShowMessage('Файл с указанным именем не найден. Действие отменено.');
Exit;
end;
Memo1.Lines.LoadFromFile(OpenDialog2.FileName);
end;
end. |