title: Save text from the clipboard to a file
body: <p>I was trying out below code that should save clipboard text to a text file in Delphi XE6. The code runs fine but generates only junk values in the output file, even when the clipboard contains a copied text fragment. How can the code be changed to work properly?</p>
  
  <pre><code>function SaveClipboardTextDataToFile(
    sFileTo : string ) : boolean;
  var
    ps1,
    ps2   : PChar;
    dwLen : DWord;
    tf    : TextFile;
    hData : THandle;
  begin
    Result := False;
    with Clipboard do
    begin
      try
        Open;
        if( HasFormat( CF_TEXT ) ) then
        begin
          hData :=
            GetClipboardData( CF_TEXT );
  
          ps1 := GlobalLock( hData );
          dwLen := GlobalSize( hData );
  
          ps2 := StrAlloc( 1 + dwLen );
  
          StrLCopy( ps2, ps1, dwLen );
  
          GlobalUnlock( hData );
  
          AssignFile( tf, sFileTo );
          ReWrite( tf );
          Write( tf, ps2 );
          CloseFile( tf );
  
          StrDispose( ps2 );
  
          Result := True;
        end;
      finally
        Close;
      end;
    end;
  end;
  </code></pre>