powered by simpleCommunicator - 2.0.60     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Delphi [игнор отключен] [закрыт для гостей] / Свой формат файла
19 сообщений из 19, страница 1 из 1
Свой формат файла
    #32172509
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Надо создать свой формат файла , например *.pg

структура файла

TMyfile = record
ID:integer;
end;

Сохранить его на диске с расширением *.pg, чтобы потом можно было открыть его редактором.

Объясняю для чего. Существует объект БД. Файл будет выполнять роль указателя на этот объект в файловой структуре. При обработке этого файла редактором, он должен извлечь из него ID, обратиться к БД и получить данные об объекте БД. Все.
Подскажите пути решения.

Не знаю как создать, сохранить и прочитать этот файл...
Заранее благодарен.
...
Рейтинг: 0 / 0
Свой формат файла
    #32172516
RoVS
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
FileCreate
FileRead
FileWrite
FileClose
...
Рейтинг: 0 / 0
Свой формат файла
    #32172518
Фотография KirillovA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Delphi Help > Index > file management routines
...
Рейтинг: 0 / 0
Свой формат файла
    #32172561
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Посмотрите, что не так?
Код: plaintext
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.
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, StdCtrls;

type

  TMyfile = record
    ID:integer;
    Name:string;
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  FileHandle: Integer;
  Data:TMyfile;
begin
    FileHandle := FileCreate('c:\MyDocument.pg');
    { Write out the length of each string, followed by the string itself. }
    Data.ID:= 0 ;
    Data.Name:=Edit1.Text;
    FileWrite(FileHandle,Data,SizeOf(Data));
    FileClose(FileHandle);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  FileHandle: Integer;
  Data:TMyfile;
begin
    FileHandle := FileOpen('c:\MyDocument.pg', 1 );
    { Write out the length of each string, followed by the string itself. }
    FileRead(FileHandle,Data,SizeOf(Data));
    Edit2.Text:=Data.Name;
    FileClose(FileHandle);
end;

end.
...
Рейтинг: 0 / 0
Свой формат файла
    #32172564
RoVS
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
FileRead|FileWrite нужно передавать указатель на данные.
...
Рейтинг: 0 / 0
Свой формат файла
    #32172580
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А как их передавать?
FileWrite(FileHandle,Pointer(Data),SizeOf(Data));
или
FileWrite(FileHandle,^Data,SizeOf(Data));
не прокатывает...
...
Рейтинг: 0 / 0
Свой формат файла
    #32172587
Фотография KirillovA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Delphi Help > Index > file management routines
там екзамплы на абсолютно все функции...
...
Рейтинг: 0 / 0
Свой формат файла
    #32172597
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Уважаемый KirillovA.
Там есть пример записи в файл строки и прочей чешуи.
Мне надо сохранить структуру

TMyfile = record
ID:integer;
Name:string;
end;

Я понимаю, что все так же как и с обычной строкой, но почему не считывается значение при
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
procedure TForm1.Button2Click(Sender: TObject);
var
  FileHandle: Integer;
  Data:TMyfile;
begin
    FileHandle := FileOpen('c:\MyDocument.pg', 1 );
    { Write out the length of each string, followed by the string itself. }
    FileRead(FileHandle,Data,SizeOf(Data));
    Edit2.Text:=Data.Name;
    FileClose(FileHandle);
end;

понять не могу...
...
Рейтинг: 0 / 0
Свой формат файла
    #32172616
Papka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Voobsse ja bi delal kak v helpe:
type

PhoneEntry = record
FirstName, LastName: string[20];
PhoneNumber: string[15];
Listed: Boolean;
end;
PhoneList = file of PhoneEntry;
...
Рейтинг: 0 / 0
Свой формат файла
    #32172629
RoVS
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Точно не помню как это выглядит в Паскале (читай справку), но примерно так:
Код: plaintext
FileRead(FileHandle,^Data,SizeOf(Data));
...
Рейтинг: 0 / 0
Свой формат файла
    #32172727
Фотография KirillovA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
VCL Reference
FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example

The following example uses a button, a string grid, and a Save dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the contents of the string grid are written to the specified file. Additional information is also written to the file so that it can be read easily with the FileRead function.

procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then

raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount – 1 do
begin

for Y := 0 to StringGrid1.RowCount – 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;

end;
---------------------------------------------------
VCL Reference
FileSeek function

See also Example

Repositions read/write point.

Unit

SysUtils

Category

file management routines

function FileSeek(Handle, Offset, Origin: Integer): Integer; overload;
function FileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64; overload;

Description

Use FileSeek to reposition the read/write point in a file that was opened with FileOpen or FileCreate. Handle is the file handle that was returned by FileOpen or FileCreate.

Offset specifies the number of bytes from Origin where the file pointer should be positioned. Origin is a code with three possible values, denoting the beginning of the file, the end of the file, and the current position of the file pointer.

Origin Action

0 The file pointer is positioned Offset bytes from the beginning of the file.
1 The file pointer is positioned Offset bytes from its current position.
2 The file pointer is positioned Offset bytes from the end of the file.

If FileSeek is successful, it returns the new position of the file pointer; otherwise, it returns -1.

Note: Do not mix routines that take or return file handles with those that use Pascal file variables (typically seen as var F). To move the file pointer in a file specified by a Pascal file variable, use the Seek procedure instead.






VCL Reference
FileOpen, FileSeek, FileRead Example


The following example uses a button, a string grid, and an Open dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the specified file is opened, read into a buffer, and closed. Then the buffer is displayed in two columns of the string grid. The first column contains the character values in the buffer. The second column contains the numeric values of the characters in the buffer.

procedure TForm1.Button1Click(Sender: TObject);

var
iFileHandle: Integer;
iFileLength: Integer;
iBytesRead: Integer;
Buffer: PChar;
i: Integer
begin
if OpenDialog1.Execute then
begin
try
iFileHandle := FileOpen(OpenDialog1.FileName, fmOpenRead);
iFileLength := FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
Buffer := PChar(AllocMem(iFileLength + 1));
iBytesRead := FileRead(iFileHandle, Buffer, iFileLength);
FileClose(iFileHandle);

for i := 0 to iBytesRead-1 do
begin
StringGrid1.RowCount := StringGrid1.RowCount + 1;
StringGrid1.Cells[1,i+1] := Buffer ;
StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer));
end;
finally
FreeMem(Buffer);
end;
end;
end;
...
Рейтинг: 0 / 0
Свой формат файла
    #32172729
Фотография KirillovA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Можно юзать связку еще с досовского паскаля Write фор типизед файлес и Seek и Read и все такое - короче екзамплы гляди по ним.... а то адми мне башку за спуффинг оторвет ...
...
Рейтинг: 0 / 0
Свой формат файла
    #32172898
oleg_e
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
procedure TForm1.Button1Click(Sender: TObject);
var Data: TMyfile;
    F: File;
begin
    AssignFile(F, 'c:\MyDocument.pg');
    Rewrite(F); // или Append, если надо добавить
    Data.ID:= 1 ;
    Data.Name:=Edit1.Text;
    BlockWrite(f, Data, SizeOf(Data));
    CloseFile(F);
end;

procedure TForm1.Button2Click(Sender: TObject);
var Data: TMyfile;
    F: File;
begin
    AssignFile(F, 'c:\MyDocument.pg');
    Reset(F);
    BlockRead(f, Data, SizeOf(Data));
    Edit1.Text:=Data.Name;
    CloseFile(F);
end;
...
Рейтинг: 0 / 0
Свой формат файла
    #32173645
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Спасибо конечно, Олег!
Но что то не считывает...
...
Рейтинг: 0 / 0
Свой формат файла
    #32173793
Фотография daw
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
> что то не считывает...
ну еще бы! Вы не пробовали посмотреть, чему равно SizeOf(Data)? ;)
...
Рейтинг: 0 / 0
Свой формат файла
    #32173794
Dmitri Krizhanovski
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: plaintext
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.
type
  PhoneEntry = record
    FirstName, LastName: string[ 20 ];
    PhoneNumber: string[ 15 ];
    Listed: Boolean;
  end;
  PhoneList = file of PhoneEntry;

procedure TForm1.bnWriteClick(Sender: TObject);
var
  List1: file of PhoneEntry;
  Data: PhoneEntry;
begin

  AssignFile( list1, 'c:\test.pg' );

  Rewrite( list1 );  // or Reset( list1 ) if exists;

  Data.FirstName := 'first name';
  Data.LastName := 'last name';
  Data.PhoneNumber := '111';
  Data.Listed := False;

  Write( list1, Data );

  Data.FirstName := 'FIRST NAME';
  Data.LastName := 'LAST NAME';
  Data.PhoneNumber := '999';
  Data.Listed := True;

  Write( list1, Data );

  CloseFile(list1);


end;

procedure TForm1.bnReadClick(Sender: TObject);
var
  List1: file of PhoneEntry;
  Data: PhoneEntry;
begin

  AssignFile( list1, 'c:\test.pg' );
  Reset( list1 );

  while not eof(list1) do begin
    Read( list1, Data );

    if Data.Listed then
      ShowMessage( Format( 'FIRST=%s, LAST=%s, PHOME=%s', [Data.FirstName, Data.LastName, Data.PhoneNumber] )  )
    else
      ShowMessage( Format( 'first=%s, last=%s, phone=%s', [Data.FirstName, Data.LastName, Data.PhoneNumber] )  );

  end;

  CloseFile(list1);

end;
...
Рейтинг: 0 / 0
Свой формат файла
    #32173806
Dmitri Krizhanovski
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
вдогонку.

Если в структуре должны быть строковые данные - указывайте их размер:
name: string[20]
...
Рейтинг: 0 / 0
Свой формат файла
    #32174114
Фотография Groove
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dmitri Krizhanovski

О Г Р О М Н О Е С П А С И Б О ! ! !

Прям как камень с души
...
Рейтинг: 0 / 0
Свой формат файла
    #32174224
Serge_S
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
record
ID: integer;
S: string;
end;

S - это указатель. Длина структуры 8 байт. Строку надо отдельно ...
А вот с длиной наверное работает на тогда длина строки макс. 255 байт
...
Рейтинг: 0 / 0
19 сообщений из 19, страница 1 из 1
Форумы / Delphi [игнор отключен] [закрыт для гостей] / Свой формат файла
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]