Reputation: 51
I didn't use filewrite a lot of time.
I made this procedure and received the next error: E2036 Variable required (on flen variable in filewrite).
procedure TForm1.WriteFN(const PIN: integer);
var
lFile: integer;
flen : integer;
begin
flen := 2;
lFile := FileOpen('/sys/pins', fmOpenWrite);
try
if filewrite(lFile, PChar(IntToStr(PIN)), flen) = -1 then
raise Exception.CreateFmt('Cannot export PIN%d', [PIN]);
finally
fileclose(lFile);
end;
end;
How to solve this problem?
Delphi Rio, Win10.
Upvotes: 0
Views: 405
Reputation: 596497
The second parameter of FileWrite()
is an untyped const
. Whatever you pass to it gets passed by reference, and as such you have to give it a real variable to refer to. In this case, you can simply dereference the PChar
pointer, that will let the parameter reference the 1st Char
in the temporary String
you are creating, eg:
FileWrite(lFile, PChar(IntToStr(PIN))^, flen)
Note, however, that FileWrite()
operates on raw bytes, not on string characters. You are telling FileWrite()
to write exactly 2 bytes, which may or may not work properly, depending on which version of Delphi you are using, and what value the PIN
contains.
Try this instead:
procedure TForm1.WriteFN(const PIN: integer);
var
lFile: integer;
flen : integer;
s: AnsiString;
begin
s := AnsiString(IntToStr(PIN));
flen := Length(s);
lFile := FileOpen('/sys/pins', fmOpenWrite);
if lFile = -1 then
raise Exception.CreateFmt('Cannot create file to export PIN%d', [PIN]);
try
if FileWrite(lFile, PAnsiChar(s)^, flen) = -1 then
raise Exception.CreateFmt('Cannot write to file to export PIN%d', [PIN]);
finally
FileClose(lFile);
end;
end;
If you are using a modern version of Delphi, consider using TFile.WriteAllText()
instead:
uses
..., System.IOUtils;
procedure TForm1.WriteFN(const PIN: integer);
begin
try
TFile.WriteAllText('/sys/pins', IntToStr(PIN));
except
Exception.RaiseOuterException(
Exception.CreateFmt('Cannot export PIN%d', [PIN])
);
end;
end;
Upvotes: 2