[fpc-pascal] accessing files from a function
Anton Shepelev
anton.txt at gmail.com
Mon May 16 21:41:00 CEST 2011
Rainer Stratmann:
> Alternatively you can make a class or an object with the
> text variable in it.
But if you need to work with only one file, you can get rid
of a global variable in the main module by just extracting
the relevant functions and the file handle into a separate
unit:
---------- myfile.pas -------------------------------------
Unit MyFile;
Interface
Procedure OpenFile(fullname: ShortString);
Function ReadNextLine(): ShortString;
Procedure CloseFile();
Function IsFileRead(): Boolean;
Implementation
var
TheFile: TEXT;
Procedure OpenFile(fullname: ShortString);
begin
Assign(TheFile, fullname);
Reset(TheFile);
end;
Function ReadNextLine(): ShortString;
var
line: ShortString;
begin
ReadLn(TheFile, line);
ReadNextLine := line;
end;
Procedure CloseFile();
begin
Close(TheFile);
end;
Function IsFileRead(): Boolean;
begin
IsFileRead := Eof(TheFile);
end;
end.
----------- filetest.pas ---------------------------------
Program ftest;
uses MyFile;
begin
OpenFile('test.txt');
While not IsFileRead() do
WriteLn(ReadNextLine());
CloseFile();
end.
----------------------------------------------------------
Anton
More information about the fpc-pascal
mailing list