Page 1 of 1

Encoding a text file.

Posted: Mon Aug 06, 2012 3:33 pm
by Davy
I want to encode a text file and have been looking at the pb cipher options. Base64Encoder() seems the most appropriate, but I'm not sure how to go about using it as the example given in the manual is only for a fragment of text. Suppose I have a file "myfile.txt". How do I encode the file in one go? presumably I need to get the length of the file first before encoding it.

Thanks in advance!

Re: Encoding a text file.

Posted: Mon Aug 06, 2012 4:08 pm
by infratec
Hi,

this should work:

Code: Select all

File = ReadFile(#PB_Any, "myfile.txt")
If File
  FileSize = Lof(File)
  *InBuffer = AllocateMemory(FileSize)
  If *InBuffer
    ReadData(File, *InBuffer, FileSize)
    OutBufferSize = FileSize * 1.4
    *OutBuffer = AllocateMemory(OutBufferSize)
    If *OutBuffer
      OutSize = Base64Encoder(*InBuffer, FileSize, *OutBuffer, OutBufferSize)
      If OutSize > 0
        OutFile = CreateFile(#PB_Any, "myEncodedFile.txt")
        If OutFile
          WriteData(OutFile, *OutBuffer, OutSize)
          CloseFile(OutFile)
        EndIf
      EndIf
      FreeMemory(*OutBuffer)
    EndIf
    FreeMemory(*InBuffer)
  EndIf
  CloseFile(File)
EndIf
Bernd

Re: Encoding a text file.

Posted: Mon Aug 06, 2012 4:30 pm
by Davy
Thanks infratec! you guys are awesome. :D

Just wondering why you made the OutBufferSize 1.4*FileSize, is that % increase recommended for this type of encoding?

Re: Encoding a text file.

Posted: Mon Aug 06, 2012 5:51 pm
by Paul
Davy wrote:Thanks infratec! you guys are awesome. :D

Just wondering why you made the OutBufferSize 1.4*FileSize, is that % increase recommended for this type of encoding?

Did you look at the help file at all?
Result = Base64Encoder(*InputBuffer, InputSize, *OutputBuffer, OutputSize)
Description

Encodes the specified buffer using the Base64 algorithm. This is widely used in e-mail programs but can be useful for any other programs which need an ASCII only (7 bit, only from 32 to 127 characters) encoding for raw binary files.
Parameters

*InputBuffer Specifies the buffer containing the plain data.
InputSize Specifies the size of the input buffer.
*OutputBuffer Specifies the output buffer where the encoded data will be copied.
OutputSize Specifies the size of the output buffer.

The output buffer should be at last 33% bigger than the input buffer, with a minimum size of 64 bytes. It's recommended to get a slightly larger buffer, like 35% bigger to avoid overflows.

Re: Encoding a text file.

Posted: Mon Aug 06, 2012 6:30 pm
by Davy
Didn't notice that. :oops: I know - RTFM.

Re: Encoding a text file.

Posted: Mon Aug 06, 2012 6:53 pm
by Paul
:wink: