A simple StringToFile() procedure

Tags: #<Tag:0x00007fc0dea6d488>

These days the easiest way to save the contents of a string to a file is to use StringTheory’s SaveFile() method.

But in case you need share a code sample with somebody who you are not sure owns StringTheory, here is a simple procedure you can paste in your code:

  MAP
StringToFile    PROCEDURE(STRING pStr,STRING pFileName)
  END

...

StringToFile        PROCEDURE(STRING pStr,STRING pFileName)
bufSize               EQUATE(32768)
dosFile               FILE,DRIVER('DOS'),CREATE
buf                     RECORD;STRING(bufSize).
                      END
pos                   LONG(1)
  CODE
  dosFile{PROP:Name} = pFileName
  CREATE(dosFile)
  IF ERRORCODE() THEN STOP(ERRORCODE()&' '&ERROR()&' '&ERRORFILE());RETURN.
  OPEN(dosFile)
  LOOP UNTIL pos > LEN(pStr)
    dosFile.Buf = pStr[ pos : LEN(pStr) ]
    ADD(dosFile,CHOOSE(pos + bufSize > LEN(pStr), |
      LEN(pStr) - pos + 1, |
      bufSize))
    pos += bufSize
  .
  CLOSE(dosfile)

I tried to make this code as short as possible without making it too cryptic. I wrote it as part of a very simple unit testing app I’m currently using to tests classes. You can find it here.

SystemStringClass.ToFile has very similar code and same disadvantages.

Hi Carlos,

Yeah as Mike points out the built-in Clarion SystemStringClass has many methods that work the same as StringTheory so easiest way would be…
!*** after Global Includes embed point ***
include(‘SystemString.inc’),once

!*** declare a SystemStringClass object ***
sysString SystemStringClass

CODE
            !*** load the sysString object with text (many ways to do this ***
	sysString.FromString('Hello World')
	sysString.ToFile(path() & '\Test.TXT')
2 Likes

Hi Graham & Mike

SystemStringClass was introduced with C9, but wasn’t available in my installation of C9.1PE. It was when I upgraded to C11EE. I had the idea it was EE only, but it looks like it’s now also included in PE.

Anyway, this code should work in even older versions.

Mike

It’s probably more efficient to use CreateFile/WriteFile API calls like you did in CJSON, but in this case I wanted to use only Clarion code, just a personal preference for the TestApp project.

Thanks to both for the replies, regards.

Carlos

Friends don’t let friends live without StringTheory… :slight_smile:

1 Like