Domanda

I'm working with files in free pascal and I'm trying to open a file, but if it doesn't exists then I create it.

This is my code:

program messages;

const PATH_ = 'data/messages/';

type messageFields = 
        record
            date : String
          ; viewed : Boolean
          ; text : String
          ; sender : String [ 8 ]
      end
  ; messagesFile = file of messageFields 
  ;

procedure openMessagesFile ( var _file: messagesFile; _fileName: String; var error: Boolean );
  begin
    error := false;
    assign ( _file, PATH_+_fileName );
    {$I-}
    reset ( _file );
    {$I+}   
    if ( ioResult <> 0 ) then
      error := true;
  end;

var _file: messagesFile
  ; fileName: String
  ; error: boolean;
begin
  readln(filename);
  openMessageFile(_file, filename, error);
  if ( error ) then
    rewrite(_file);
end.

The first time that I execute the program, since the file doesn't exists, throw me an exception. The second time, works fine!

This is the exception:

An unhandled exception occurred at $00401759 :
EInOutError : Access denied
È stato utile?

Soluzione

Have you reproduced this error with the exact code you've posted and I really can't see it causing the error you're getting. I cannot reproduce it and since you haven't included uses SysUtils you should get Runtime error 5 instead of EInOutError.

One thing that's terribly wrong with your code is that you're not closing the file after opening/creating it (although OS usually cleans it up after program finishes). Given this and the fact that you're getting EInOutError instead of Runtime error 5 I believe that your (real, bigger) program keeps the file open after creating it and trying to open it later, but fails since the file is already opened. The second time you run the program the file is already created so it's only opened once (for reading).

Altri suggerimenti

The code is a bit atypical, but Windows is known to keep fleeting locks on files for a few seconds even after they are closed and Dos originating code like this might suffer from that.

Maybe using FPC's FileExist() directly works better (IIRC on windows it is findfirst based, and not createfile based)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top