Martin Brláž
Martin Brláž

Reputation: 53

Lazarus error: Can't take the address of constant expressions

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

Answers (2)

Ken White
Ken White

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

hy-soft
hy-soft

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

Related Questions