The weird Rewrite bug lazarus / 21-General ---------------------------------------------------------------------- fxeconomist · 2024-04-16 21:10 So I just hit this thing, A file that was written cannot be Rewritten (the second time, creation works). Not only that, but assign & erase also don't do anything. File just needs to be written once. assign(f,'fullpath'); rewrite(f);...close(f); Yes, rewrite is between {$I-} {$I+}. This had no effect. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TToroidCoil.SaveToFile(fullpath:string);var f:text;i:word;beginassign( f,fullpath);{$I-}rewrite(f);{$I+}writeln(f,'# Coil Parameters');//close(f);  I ran this similar code in FPC with no trouble: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   assign(f,'e:\testfilerewrite.txt');  rewrite(f);  write(f,random()*100000000);  except     on E: Exception do writeln('I/O error');  end;  close(f); ---------------------------------------------------------------------- ojz0r · 2024-04-17 01:50 Try to use: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  f: TextFile;...AssignFile(f,fullpath);...CloseFile(f);  And see if it works. Edit: Missed some code. ---------------------------------------------------------------------- fxeconomist · 2024-04-17 07:50 Quote from: ojz0r on April 17, 2024, 03:50:28 amTry to use: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  f: TextFile;...AssignFile(f,fullpath);...CloseFile(f);  And see if it works. Edit: Missed some code. This code is from SmartPascal. Quote from: jamie on April 16, 2024, 11:27:36 pmSetting the {$i-} only prevents your program from crashing, it does not ignore the IOresults.. If there is a lingering IO error, these functions will be not execute. So at some point in code, you may have had an error and has set the InOutRes variable to something other than 0. you should always test IoResult at some point which will report the current error and also clear it. Allright, so I turned on my computer today and amended the code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TToroidCoil.SaveToFile(fullpath:string):Word;var f:text;i:word;r:word; beginassign(f,fullpath);{$I-}rewrite(f);{$I+}r:=IOResult;if r<>0 then begin SaveToFile:=r;exit;end;writeln(f,'# Coil Parameters');//close(f);SaveToFile:=0;end;  and then the caller. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i rocedure TForm1.btnSaveAsOBJClick(Sender: TObject);var filename:string;i,reply:integer;error:word;begin  SaveDialog1.Title:='Save coil as .OBJ file';  if SaveDialog1.Execute then  begin      Filename := Savedialog1.filename;      if pos('.', Savedialog1.filename) > 0 then      begin        I := pos('.', Savedialog1.filename);        if uppercase(Copy(Savedialog1.filename, I + 1, 3)) <> 'OBJ' then          filename := copy(filename, 1, I) + 'obj';      end      else      begin        filename := savedialog1.filename + '.obj';      end;      if FileExists(filename) then reply:=MessageBox(0,'File exists! Overwrite ?','Save as .OBJ',MB_YESNO);                              end else reply:=IDYES;    if reply=IDYES then begin         error:=MyToroid.SaveToFile(filename);         if error<>0 then ShowMessage('An Error Occured!' + #13 +' (error code '+int2str(error,0)+')');      end;end;  Ran the program, told it to rewrite the file it made last night. Bang, error 5, access denied. It was so denied I couldn't even delete it manually from Total Commander! Now, I understand there is something funny. I remember encountering similar problems when I was coding in FoxPro. FoxPro has the FOPEN() function, which doesn't ever work in a rewrite mode. I mean if you read the documentation here ( https://hackfox.github.io/section4/s4g194.html ) you might say, "Well, we just do a fhandle=FOPEN(filename,1)" But that doesn't work. For this reason, I had to write a zillion years ago a workaround to restore file functions functionality the way did work in BP 7 at that time. procedure AssignReset parameters filename,filehandle filehandle=FOPEN(filename,0) return procedure AssignRewrite parameters filename,filehandle if file(filename)==.F.    filehandle=FCREATE(filename,0) else    set safe off    delete file (filename)    set safe on    filehandle=FCREATE(filename,0) endif return procedure AssignAppend parameters filename,filehandle if file(filename)==.F.    filehandle=FCREATE(filename,0) else    filehandle=FOPEN(filename,0)    =FSEEK(filehandle,FileSize(filehandle)) endif return Problem is, this workaround doesn't work here in Pascal. If I check if FileExists() and do assign(f);erase(f); then this doesn't work as well. ---------------------------------------------------------------------- cdbc · 2024-04-17 08:06 Hi Hold on... I remember that for text-files, in order to edit/update them, you 'read' the file -> edit said file in memory -> then you *create* a new file with a slightly different name, write the contents to that file -> then you delete the original file -> then you rename the new file to the original name => file edited. This is special for text-files. Binary files are seekable, thus you can reopen them and write data at arbitrary positions. I think this is where your /5 ~ Access denied/ comes from...  Regards Benny ---------------------------------------------------------------------- Nitorami · 2024-04-17 08:55 I don't know what exactly is going on in your code, but when using the DOS file assign/read/write procedures, you must check the IOResult generated by the OS each time you read or write a block of data to the file, not just after opening it.  IOResult is a simple integer value generated by the OS' I/O Routines, and reading it resets it to zero. Failing to read/reset it will get you into trouble with the next IO Access. I found in BP times that handling this correctly may be a bit tricky. As an old timer, I am used to these old read/write routines from MSDOS times, and I still use them. There are alternatives now like FileCreate/FileOpen/FileClose etc, but I believe they just do the Error Checking internally and wrap an exception handler around. ---------------------------------------------------------------------- Bart · 2024-04-17 11:03 For me this (slightly modified) code works as expected: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program test;{$ifdef fpc}{$mode objfpc}{$h+}//{$mode delphi}{$H+}{$endif}{$apptype console} uses  SysUtils; function SaveToFile(fullpath:string):Word;var  f:textfile;begin  AssignFile(f,fullpath);   //AssignFile is the same as System.Assign  {$I-}  Rewrite(f);  Result:=IOResult;  //<< this will reset InOutRes to zero  if Result<>0 then    Exit;  Writeln(f,'# Coil Parameters');  Result:=IOResult;  if Result<>0 then    Exit;  CloseFile(f);  // CloseFile is the same as System.Close  Result := IOResult;  {$I+}  SaveToFile:=0;end; var  Fn: String;  Res: Word; begin  repeat    write('Filename: ');    readln(Fn);    if Fn<> '' then    begin      Res := SaveToFile(Fn);      if Res=0 then        writeln('Ok')      else        writeln('Fail: Res=',Res);    end;  until Fn='' ;end. When I try to rewrite the same file over and over, it works just fine: Code: [Select]C:\Users\Bart\LazarusProjecten\ConsoleProjecten>test Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: foo.bar Ok Filename: C:\Users\Bart\LazarusProjecten\ConsoleProjecten>type foo.bar # Coil Parameters Notice that I check IOResult after each read/write/rewrite/closefile (as Nitorami already pointed out). Bart ---------------------------------------------------------------------- Kays · 2024-04-17 11:23 Quote from: fxeconomist on April 16, 2024, 11:10:22 pm[…] rewrite is between {$I-} {$I+}. […]Quote from: Kays on October 23, 2023, 03:06:03 pmQuote from: prof7bit on October 23, 2023, 02:09:44 pm[…] Is this intended behavior? […]This is a user error. The documentation of {$IOChecks} states:QuoteThe effect of this is that IOResult must be checked after each I/O operation for subsequent I/O operations to succeed.It says “must be checked.” If you insert a call to system.IOResult after each potentially failing I/O operation, subsequent I/O operations remain unaffected. ---------------------------------------------------------------------- PascalDragon · 2024-04-18 19:58 Quote from: Nitorami on April 17, 2024, 10:55:05 amI don't know what exactly is going on in your code, but when using the DOS file assign/read/write procedures, you must check the IOResult generated by the OS each time you read or write a block of data to the file, not just after opening it.  IOResult is a simple integer value generated by the OS' I/O Routines, and reading it resets it to zero. Failing to read/reset it will get you into trouble with the next IO Access. I found in BP times that handling this correctly may be a bit tricky. This depends on the setting of the {$I} switch. If it is {$I-} then one needs to check IOResult manually. If it is {$I+} then the compiler will automatically insert checks that trigger a runtime error. If the SysUtils unit is used in the program that runtime error will be converted to a EInOutError and thus can be handled using ordinary Object Pascal exception handling. ---------------------------------------------------------------------- fxeconomist · 2024-05-05 13:55 No No No It still doesn't work. And as proof, I made a Bandicam record. Yes, the file is still declared as text ; i changed it to textfile and it still does the same. I put up a Bandicam record of it. Watch it quickly, won't stay long! https://streamable.com/fovo6o ---------------------------------------------------------------------- dseligo · 2024-05-06 11:39 What OS and filesystem is that? Did you try some other location or USB flash drive? Do you have some special file/directory permissions? Do you run some AV software, cloud synchronisation, backup software or something similar which could interfere with filesystem? Did you try to test it on different computer? ---------------------------------------------------------------------- Thaddy · 2024-05-07 15:04 There is no weird rewrite bug. he needs to keep the handle open and use append. that was already mentioned? Or if the handle is closed open it and do append(handle). The proper way to handle this is - of course again - in the manuals: https://www.freepascal.org/docs-html/rtl/system/seek.html https://www.freepascal.org/docs-html/rtl/system/append.html#:~:text=Ap pend%20opens%20an%20existing%20file%20in%20append%20mode.,is%20not%20t aken%20into%20account%20when%20calling%20Append. Full example. note:  Filemode=2 meaning r/w. and then reset, not rewrite and then append. More docs: https://www.freepascal.org/docs-html/rtl/system/filemode.html So, now, what? is weird? It has always been that way. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program filehandling;var  Handle:Text;  Fn:string = 'test.txt';begin  Assign(Handle,Fn);  Rewrite(Handle);  writeln(Handle, 'First part');  Close(Handle);    FileMode := 2; // open read/write    Assign(Handle, Fn);  Reset(Handle);// NOT rewrite  Append(Handle);//Goto eof  Writeln(Handle,'Second part');  Close(Handle);  // You may want to restore filemode hereafter.end.Code: Bash  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i cat test.txtFirst partSecond partPlease read the manuals first, ask later. ---------------------------------------------------------------------- Thaddy · 2024-05-07 16:26 Works on all platforms btw, it is essential Pascal. (Take note, Bart and the others) The only thing I can think of that if two different processes are handling the same file, just set the handle for text to nil. Unlikely. It is the filemode. ---------------------------------------------------------------------- tetrastes · 2024-05-07 19:24 Quote from: Thaddy on May 07, 2024, 05:04:21 pmPlease read the manuals first, ask later. Yes. From manuals: 1. QuoteFileMode determines how untyped files are opened for reading with Reset.Not Text. 2. OP needs exactly Rewrite, not Append. And it should work. https://www.freepascal.org/docs-html/rtl/system/rewrite.html: Quoteif Rewrite finds a file with the same name as F, this file is truncated to length 0. ---------------------------------------------------------------------- Thaddy · 2024-05-07 19:59 Does he really wants to kill the file? That was not clear to me. The code looks he wants to append. Anyway, if an application holds a lock and another application tries to interfear with that, good luck, close and nil the handle. And untyped or typed files does not matter. (at all! ) Reading IOResult in{$I-} state would have told him the file exists or not. You are being silly and got me angry ( last time well over a year ago) You deliberatly interpret the documentation wrong. The only difference between file of text and an untyped file is that you need to use blockwrite with a proper length and check eof. again basic pascal. ---------------------------------------------------------------------- tetrastes · 2024-05-07 20:53 Clean your glasses and reread the first post. Untyped or typed files do matter for FileMode, which has nothing to do with Text files, and which your speculations were about. I know that people with dementia get angry easily, but still please try to avoid insults. ---------------------------------------------------------------------- fxeconomist · 2024-05-07 23:36 Quote from: dseligo on May 06, 2024, 01:39:58 pmWhat OS and filesystem is that? Did you try some other location or USB flash drive? Do you have some special file/directory permissions? Do you run some AV software, cloud synchronisation, backup software or something similar which could interfere with filesystem? Did you try to test it on different computer? It's just Windows 11. Location is the same, I showed you that it makes the file in the beginning, and then it doesn't want to rewrite() for overwriting. Location is nothing special, a folder on my data partition on the big SSD drive that replaced the older HDD. There is nothing that can possibly interfere with that. Ok, I'll get it to run on a Windows VM... ---------------------------------------------------------------------- fxeconomist · 2024-05-07 23:39 Quote from: Thaddy on May 07, 2024, 05:04:21 pmThere is no weird rewrite bug. he needs to keep the handle open and use append. that was already mentioned? Or if the handle is closed open it and do append(handle). The proper way to handle this is - of course again - in the manuals: https://www.freepascal.org/docs-html/rtl/system/seek.html https://www.freepascal.org/docs-html/rtl/system/append.html#:~:text=Ap pend%20opens%20an%20existing%20file%20in%20append%20mode.,is%20not%20t aken%20into%20account%20when%20calling%20Append. Full example. note:  Filemode=2 meaning r/w. and then reset, not rewrite and then append. More docs: https://www.freepascal.org/docs-html/rtl/system/filemode.html So, now, what? is weird? It has always been that way. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program filehandling;var  Handle:Text;  Fn:string = 'test.txt';begin  Assign(Handle,Fn);  Rewrite(Handle);  writeln(Handle, 'First part');  Close(Handle);    FileMode := 2; // open read/write    Assign(Handle, Fn);  Reset(Handle);// NOT rewrite  Append(Handle);//Goto eof  Writeln(Handle,'Second part');  Close(Handle);  // You may want to restore filemode hereafter.end.Code: Bash  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i cat test.txtFirst partSecond partPlease read the manuals first, ask later. But I don't want to append, I want to write over. It's the save button, it has to replace the file with whatever is new. ---------------------------------------------------------------------- ASBzone · 2024-05-08 01:35 What are the permissions on the file you are creating? Also, can you try to save the files somewhere else, on a different drive?  (Maybe an external one?) ---------------------------------------------------------------------- dseligo · 2024-05-08 08:24 Quote from: fxeconomist on May 08, 2024, 01:36:55 amQuote from: dseligo on May 06, 2024, 01:39:58 pmWhat OS and filesystem is that? Did you try some other location or USB flash drive? Do you have some special file/directory permissions? Do you run some AV software, cloud synchronisation, backup software or something similar which could interfere with filesystem? Did you try to test it on different computer? It's just Windows 11. Location is the same, I showed you that it makes the file in the beginning, and then it doesn't want to rewrite() for overwriting. Location is nothing special, a folder on my data partition on the big SSD drive that replaced the older HDD. There is nothing that can possibly interfere with that. Ok, I'll get it to run on a Windows VM... There *is* something that interfere with your file, that is the reason I wrote possibilities that I could think of. It could be something in your program, it could be open in external program, it could be something with OS, with AV, ... Maybe you could try at the same time (at the beginning of your SaveToFile method) to create/rewrite some other file (try in the same location and also somewhere else), just for test. See if that works or fails. ---------------------------------------------------------------------- dseligo · 2024-05-08 08:35 Oh, and I just tried your code and it doesn't compile: Error: Wrong number of parameters specified for call to "Assign" So what is your Lazarus version and mode in which you compile this? It would be best if you could make small compileable project that shows your problem and post it here. Also, in one of your posts you wrote this: QuoteThis code is from SmartPascal. What did you mean by this? ---------------------------------------------------------------------- Thaddy · 2024-05-08 08:43 Smart pascal is basically a scripting language. If he wants to overwrite, btw, he can leave out append. or use seek() if he wants to overwrite something specific.