FilterIndex (C++)
Description
This example uses an Open dialog box, a memo, and a button on a form. When you click the button, the Open dialog box appears. When you select the files in the dialog box and press the OK button, the first line from each of the files is added to the memo. Choose multiple files using the CTRL or the SHIFT key. These files need to have a UTF8 encoding, even if they contain non-Ansi characters. Any other encoding requires a user-supplied decoding. The fgets function with narrow characters should be used regardless of the encoding.
Code
#include <stdio.h> // For FILE
void __fastcall TForm1::Button1Click(TObject *Sender)
{
FILE *stream;
OpenDialog1->Options.Clear();
OpenDialog1->Options << ofAllowMultiSelect << ofFileMustExist;
OpenDialog1->Filter = L"Text files (*.txt)|*.txt|All files (*.*)|*.*";
OpenDialog1->FilterIndex = 2; // Start the dialog, showing all files.
if (OpenDialog1->Execute())
{
TStringList *Test = new TStringList;
Test->LoadFromFile(OpenDialog1->Files->Strings[0]); // Just a debugging experiment
for (int I = 0; I < OpenDialog1->Files->Count; I ++)
{
#define USE_ENCODING
#if defined(USE_ENCODING)
TBytes FirstLine; // A dynamic array of bytes
FirstLine.Length = 512;
stream = _wfopen(OpenDialog1->Files->Strings[I].c_str(), L"r");
fgets(&FirstLine[0], FirstLine.Length, stream);
Memo1->Lines->Append(TEncoding::UTF8->GetString(FirstLine));
fclose(stream);
#else
char FirstLine[512];
stream = _wfopen(OpenDialog1->Files->Strings[I].c_str(), L"r");
fgets(FirstLine, sizeof(FirstLine), stream);
Memo1->Lines->Append(UTF8String(FirstLine));
fclose(stream);
#endif
}
}
}
Uses
- Vcl.Dialogs.TOpenDialog.FilterIndex ( fr | de | ja )
- Vcl.Dialogs.TOpenDialog.Files ( fr | de | ja )
- System.Classes.TStrings.Strings ( fr | de | ja )
- System.Classes.TStrings.Append ( fr | de | ja )
- System.SysUtils.TBytes ( fr | de | ja )
- System.DynamicArray ( fr | de | ja )
- System.DynamicArray.Length ( fr | de | ja )
- System.SysUtils.TEncoding.UTF8 ( fr | de | ja )
- System.SysUtils.TEncoding.GetString ( fr | de | ja )
- System.UTF8String ( fr | de | ja )