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.
#include
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szFileName[MAXFILE+4];
int iFileHandle;
int iLength;
if (SaveDialog1->Execute())
{
if (FileExists(SaveDialog1->FileName))
{
fnsplit(SaveDialog1->FileName.c_str(), 0, 0, szFileName, 0);
strcat(szFileName, ".BAK");
RenameFile(SaveDialog1->FileName, szFileName);
}
iFileHandle = FileCreate(SaveDialog1->FileName);
// Write out the number of rows and columns in the grid.
FileWrite(iFileHandle, (char*)&(StringGrid1->ColCount), sizeof(StringGrid1->ColCount));
FileWrite(iFileHandle, (char*)&(StringGrid1->RowCount), sizeof(StringGrid1->RowCount));
for (int x=0;xColCount;x++)
{
for (int y=0;yRowCount;y++)
{
// Write out the length of each string, followed by the string itself.
iLength = StringGrid1->Cells[x][y].Length();
FileWrite(iFileHandle, (char*)&iLength, sizeof(iLength));
FileWrite(iFileHandle, StringGrid1->Cells[x][y].c_str(), StringGrid1->Cells[x][y].Length());
}
}
FileClose(iFileHandle);
}
}