in reply to What is the point of a+ and w+ when opening files?

Opening a file w+ is for creating a new blank file (or clobber the existing one if any) that you intend to use as read/write storage. a+ is when you want to use the contents of the file that are already there. You don't have to seek back to the beginning to read after a write, just seek anywhere, so it's useful for structured file databases. Of course, you would probably use a library for that, so it's more common to use it in C than in Perl.

An example use for Perl would be if you wanted to implement Capture::Tiny (capture your own stderr or stdout). You create a temp file with mode w+ and then redirect stderr into that file, run some code that may generate output, then switch stderr back to the original file handle and read from the temp file to see what got written inbetween. On Unix, if you open that file w+ you can unlink it right after creating it so it doesn't appear in the filesystem (and can't get orphaned if the process aborts) and yet still read/write the file just from that one handle. ...but most people doing this would probably use File::Temp instead of a new set of library functions that create w+ files, so maybe still not a reason for you to implement a helper function to wrap it.

But, on that note, File::Temp is probably using mode w+ for all the files it creates. So there's another reason for w+, if you want to create the most useful generic file for someone else to use and you don't know what mode they actually need.

...And that reminds me of another use - you could be receiving data from an external source and not want to risk filling main memory and crashing the program. So a framework like Catalyst reads packets from the client and writes them to a temp file, then provides that file (after seeking back to byte 0) to the application to read and be able to seek on it, or rename it into a new location since it is already on disk.

  • Comment on Re: What is the point of a+ and w+ when opening files?