ExtractFileName (C++)
Description
The following example uses a button, a string grid, and a Save dialog box on a form. When you click the button, you are prompted for a filename. When you click 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. Verify the file written after executing.
Code
#include <dir.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
wchar_t szFileName[MAXFILE+4];
int iFileHandle;
int iLength;
int count;
if (SaveDialog1->Execute())
{
if (FileExists(SaveDialog1->FileName))
{
_wfnsplit(SaveDialog1->FileName.w_str(), 0, 0, szFileName, 0);
wcscat(szFileName, L".BAK");
RenameFile(SaveDialog1->FileName, szFileName);
}
iFileHandle = FileCreate(SaveDialog1->FileName);
// Write out the number of rows and columns in the grid.
count = StringGrid1->ColCount;
FileWrite(iFileHandle, &count, sizeof(count));
count = StringGrid1->RowCount;
FileWrite(iFileHandle, &count, sizeof(count));
for (int x=0;x<StringGrid1->ColCount;x++)
{
for (int y=0;y<StringGrid1->RowCount;y++)
{
// Write out the length of each string, followed by the string itself.
iLength = StringGrid1->Cells[x][y].Length()*sizeof(wchar_t);
FileWrite(iFileHandle, (wchar_t *)&iLength, sizeof(iLength));
FileWrite(iFileHandle, StringGrid1->Cells[x][y].w_str(), iLength);
}
}
FileClose(iFileHandle);
}
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
StringGrid1->Cells[1][0] = L"Column 1";
StringGrid1->Cells[2][0] = L"Column 2";
StringGrid1->Cells[3][0] = L"Column 3";
StringGrid1->Cells[4][0] = L"Column 4";
StringGrid1->Cells[0][1] = L"Row 1";
StringGrid1->Cells[1][1] = L"Object";
StringGrid1->Cells[2][1] = L"Pascal";
StringGrid1->Cells[3][1] = L"is";
StringGrid1->Cells[4][1] = L"excellent";
StringGrid1->Cells[0][2] = L"Row 2";
StringGrid1->Cells[1][2] = L"Delphi";
StringGrid1->Cells[2][2] = L"is";
StringGrid1->Cells[4][2] = L"RAD ભ૧હ૪";
};
Uses
- System.SysUtils.FileExists ( fr | de | ja )
- System.SysUtils.RenameFile ( fr | de | ja )
- System.SysUtils.FileCreate ( fr | de | ja )
- System.SysUtils.FileWrite ( fr | de | ja )
- System.SysUtils.FileClose ( fr | de | ja )