Recent

Author Topic: Passing FileHandle to global variable  (Read 1346 times)

DaveEmu

  • Newbie
  • Posts: 5
Passing FileHandle to global variable
« on: May 22, 2018, 12:30:20 pm »
Hi,

can anyone explain why this isn't working:

Code: Pascal  [Select][+][-]
  1. PROGRAM WriteTest;
  2.  
  3. VAR
  4.         f1: TEXT;
  5.         f2: TEXT;
  6.  
  7. PROCEDURE WriteSomething(VAR f: TEXT);
  8. BEGIN
  9.   f2 := f;
  10.   Write(f2, 'Foo Bar');
  11. END;
  12.  
  13. BEGIN
  14.  
  15. Assign(f1,'test.txt');
  16. Rewrite(f1);
  17. WriteSomething(f1);
  18. Close(f1);
  19.  
  20. END.
  21.  

I'm opening the file, passing it to the procedure; working on the file in the procedure is just fine. But if i try to save it to a global variable it doesn't work anymore.

Thanks!

Thaddy

  • Hero Member
  • *****
  • Posts: 14358
  • Sensorship about opinions does not belong here.
Re: Passing FileHandle to global variable
« Reply #1 on: May 22, 2018, 12:32:59 pm »
reset?.... >:D https://www.freepascal.org/docs-html/rtl/system/reset.html
Old school Pascal IO is NOT bidirectional. (Never has been)
You are using really old syntax. In your case use a TFilestream. Or Reset...
« Last Edit: May 22, 2018, 12:42:26 pm by Thaddy »
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

DaveEmu

  • Newbie
  • Posts: 5
Re: Passing FileHandle to global variable
« Reply #2 on: May 22, 2018, 01:13:45 pm »
I'm using "rewrite", so the file is open and ready for writing. I can pass the open f1 variabe call by reference to the procedure und work with it within the procedure, but if I save the already passed f1 to a global f2 variable it stops working.

rvk

  • Hero Member
  • *****
  • Posts: 6162
Re: Passing FileHandle to global variable
« Reply #3 on: May 22, 2018, 01:59:34 pm »
If you put a Close(F2) in your WriteSomething() your data is written to the file.
That makes me expect that when F2 becomes out of scope (at the end of WriteSomething) it is closed automatically without flushing the data to the file.

So you can also do a manual Flush:
Code: Pascal  [Select][+][-]
  1.   procedure WriteSomething(var f: Text);
  2.   begin
  3.     f2 := f;
  4.     Write(f2, 'Foo Bar');
  5.     Flush(f2);
  6.   end;
That'll work too.

DaveEmu

  • Newbie
  • Posts: 5
Re: Passing FileHandle to global variable
« Reply #4 on: May 22, 2018, 02:15:47 pm »
Thanks, you are right! It's working!  :)

 

TinyPortal © 2005-2018