in reply to Why do we need to close filehandles?

Recently, a student of mine had a problem: in his program, he was creating a file. Later in the program, he was reading the file - but he did not close its file handle, which resulted in the file not being complete. The program thus returned wrong results.
  • Comment on Re: Why do we need to close filehandles?

Replies are listed 'Best First'.
Re^2: Why do we need to close filehandles?
by locked_user sundialsvc4 (Abbot) on Apr 30, 2011 at 12:25 UTC

    Bingo!   There’s a solid technical reason for paying close attention to file-handles ... buffering.   Until a file-handle is closed, it is possible that there’s some data out there which has not been written to disk.   Other applications will not see that data yet; nor will this application, necessarily, if it opens a second handle to the same file.   (Which it is, of course, free to do.)

    Obviously, the system will wipe your a*s ... clean up after you even if you don’t, but writing to a file is an action that you need to explicitly bring to a close.   Reading from the file is much more forgiving.

      There’s a solid technical reason for paying close attention to file-handles ... buffering.
      Well, you can just flush the handle; there's no need to close it. And if you do things in a logical way, you either read/write using buffered I/O, or you read/write using unbuffered I/O. In either case, you should be fine.