oblomov
oblomov

Reputation: 23

File not Found in Pascal (Reset function)

I have a problem with reading text from .txt file using Pascal. When I try to run the code I get an EXITCODE = 2 (File not Found). It crashes on the Reset function.

var
  name: string;
  c: char;
  f: text;

begin
   name := 'config.txt';
   assign(f,name);
   reset(f);
   while not eof(f) do begin
     read(f,c);
     write(c)
   end
end.

If I provide complete address to file it works as expected. The problem arises when the address is relative (as shown).

Both the code and the text file are in the same directory.

I use FreePascal Compiler version 2.6.4

Upvotes: 0

Views: 2397

Answers (3)

imbearr
imbearr

Reputation: 1019

Enable this:

Options -> Enviroment -> Preferences -> [Options] Change dir on open

... and be happy ;)

/* Actual for Turbo Pascal 7.0 */

Upvotes: 0

KS4TD
KS4TD

Reputation: 19

To solve that problem, you could do something like this (you'll need to add SysUtils to your Uses clause):

CurrentPath := GetCurrentDirectory;
If DirectoryExists(CurrentPath) And FileExists('config.txt') Then...

That will make sure that you're in the same path as the executable and make sure that the file 'config.txt' is actually there in the same directory. This is what I use under both Linux and Windows to verify if a file exists in a directory.

Hope this helps!

Upvotes: 0

oblomov
oblomov

Reputation: 23

As said @Marco van de Voort in comments the problem was in FPC running the .exe in its default directory instead of the directory it was saved in.

Upvotes: 1

Related Questions