TEncoding (C++)

From RAD Studio Code Examples
Jump to: navigation, search


This example reads any file and converts the encoding to UTF8. This example uses the TBytesStream to read the files into a TBytes and also uses the auto_ptr construction to clean up created class instances.


#include <tchar.h>
#include <memory>       //For STL auto_ptr class

#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
  // Sample to convert a file of any encoding to UTF8
  TEncoding *LEncoding = NULL;
  std::auto_ptr<TFileStream> LFileStream(new TFileStream("..\\Sample.txt", fmOpenRead));

  // Read file into buffer.
  TBytes myBytes;
  std::auto_ptr<TBytesStream> myBytesStream(new TBytesStream(myBytes));
  myBytesStream->CopyFrom(LFileStream.get(), LFileStream->Size);

  // Identify encoding and convert buffer to UTF8.
  int LOffset = TEncoding::GetBufferEncoding(myBytesStream->Bytes, LEncoding);
  if (LOffset == 0)
    return 1; // Unknown encoding; do not convert.
  myBytes = TEncoding::Convert(LEncoding, TEncoding::UTF8,
							   LOffset, myBytesStream->Size-LOffset);
  // Create output file.
  std::auto_ptr<TFileStream> DestFileStream(new TFileStream("..\\SampleUTF8.txt", fmCreate));

  // Write UTF8 byte-order mark and buffer to output file.
  TBytes LByteOrderMark;
  LByteOrderMark = TEncoding::UTF8->GetPreamble();

  // Grab preamble and write to destination.
  DestFileStream->Write(&LByteOrderMark[0], LByteOrderMark.Length);

  // Write converted buffer.
  DestFileStream->Write(&myBytes[0], myBytes.Length);
  return 0;