PDA

View Full Version : نوشتن محتوای StringGrid در فایل ,خواندن از فایل



Developer Programmer
پنج شنبه 07 اردیبهشت 1385, 10:13 صبح
سلام
لازمه که محتوای StringGrid رو در یه فایل Binary ذخیره کنیم و در مواقع لازم از فایل بازخوانی کنیم.
من از راهنمای دلفی ، کد نوشتن رو پیدا کردم ، اما اصلا نمیتونم اونچیزی رو که ذخیره کردم بخونم! :گیج:




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;

shobair
پنج شنبه 07 اردیبهشت 1385, 10:35 صبح
سلام
اگه به متن برنامه دقت کنید می بینید 2 بایت اول فایل مربوط به تعداد ستونها و 2 بایت بعدی مربوط به تعداد سطرهاست که به صورت باینری ذخیره شده و در بقیه فایل به تعداد ستونها، اطلاعات هر سطر نوشته شده. ابتدا 4 بایت اول رو بخوانید تا تعداد ستونها و سطرها معلوم شود با 2 تا حلقه for تو در تو بقیه اطلاعات را میشود خواند.
تلاش کنید که خودتون بنویسید اگه نتونستید من براتون می نویسم
شبیر

Developer Programmer
پنج شنبه 07 اردیبهشت 1385, 19:54 عصر
شبیر جان ، تلاشم رو کردم...
اشاره گر رو میبرم جلو و 4بایت میخونم اما مقدار عجیب و غریب خونده میشه!