Question

I would like to write/read a simple text file using dwscript. My code is here below... but I am non able to get it run, please someone might help...: (I am using the Simple.exe in the Demos folder of DWS installation)

// uses Classes;
{$INCLUDE_ONCE 'c:/.../System.Classes.pas'}

var
    s: TFileStream;
    o: string; // out
    i: integer;
    f: word; // flag

f := fmOpenReadWrite;
if not FileExists('C:\Temp\Junkfile.txt') then
    f := f or fmCreate;

s := TFileStream.Create('C:\Temp\Junkfile.txt', f);
try
    s.Position := s.Size;  // will be 0 if file created, end of text if not
    for i := 1 to 10 do begin
        o := Format('This is test line %d'#13#10, [i]);
        s.Write(o[1], Length(o) * SizeOf(Char));
    end;
finally
    s.Free;
end;
Was it helpful?

Solution

By default the script engine keeps everything sand-boxed and nothing that gives access outside the sandbox is exposed. So if you want to give access to arbitrary files to script you need to expose functions & classes to achieve it (through TdwsUnit f.i.).

Also it won't compile the Delphi classes unit, DWScript is not meant to be an alternative to the Delphi compiler, but to offer scripting support, ie. allow end users to run code in a way over which you have full control over what they can do, and that can't crash or corrupt the host application (that last point being the key differentiation with the other notable Pascal scripting engines).

You can use dwsFileFunctions to get basic file I/O support, in which case an equivalent to the file creation portion of your code would be something like

var f := FileCreate('C:\Temp\Junkfile.txt');

for var i := 1 to 10 do
   FileWrite(f, Format('This is test line %d'#13#10, [i]));

FileClose(f);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top