Reputation: 53
i want to make a simple program to read files in lazarus. But when i try to read a line from txt file compiler give me this error: "Can't take the address of constant expressions"
There is that problematic part -
system.Assign(MyFile, label1.caption + '.txt');
reset(MyFile);
Readln(MyFile,name); - this give that error
Any suggestion to solve this?
Upvotes: 1
Views: 1913
Reputation: 125679
From what you've posted (especially the label1.caption
), it appears this is from an event handler on a form. In that case, name
most likely scopes to Form1.Name
, which is not a variable but a property of the form itself.
Declare a variable of the proper type, and read into it instead. For instance, to read a line of text (example tested in a console application):
program Test;
uses
SysUtils;
var
Buffer: array[0..255] of Char; // Reads up to 256 characters in a line
LineData: string;
begin
System.Assign(MyFile, 'C:\Temp\Test.txt');
Reset(MyFile);
ReadLn(MyFile, Buffer);
LineData := Buffer;
// Do something with LineData
WriteLn(LineData);
ReadLn;
end.
A much better alternative would be to move away from the old IO functions and into the modern world. For instance, you can use the `Classes.TStreamReader' instead:
program Test;
uses
SysUtils, Classes;
var
LineData: string;
Reader: TStreamReader;
begin
Reader := TStreamReader.Create('C:\Temp\Test.txt');
try
LineData := Reader.ReadLine;
WriteLn(LineData);
ReadLn;
finally
Reader.Free;
end;
end.
Upvotes: 1
Reputation: 173
I tested it and came to the following conclusion: 1.) it's a compiler message - not a runtime-error! 2.) You haven't declared "name" at all. So the property 'name' of the form you're in is taken - and this leads to exact that error.
Solution: Declare a string to put the lines into
var sTextLine:string;
begin
//...
Readln(Myfile,,sTextLine);
//...
end;
Upvotes: 0