And if you do ls again, one second later, all of those files might be
gone or different sized. If you relied on the answer that you got,
you would (at best) get the wrong answer on occasion. If you expected
that the size you got would hold all of the file, and if someone added
a record, then your memory allocation to hold it is too small and when
you read the data, the operation will overwrite memory. If you can
come up with a simple work-around for this obvious and fundamental
problem, I would like to hear of it. ....
I am surprised that you do not understand the ramifications of not
being the only one allowed to access a file.
I've stayed out of this part of the discussion, but I've decided that I
have to defend at least this aspect of Jacob's code. Sure, it's possible
for a file to change it's contents while you are working on it.
However, whether or not it's necessary or even appropriate to write code
which copes with that possibility depends upon the application.
I only remember one time in the last 3 decades where I wrote a program
which was actually intended to produce it's desired results despite the
possibility that it's input file might change while reading it. That
program worked by making sure the file didn't change, by using POSIX
file and record locking (I remember that I needed both file and record
locking in the same program - obviously not for the same file). For most
of the other programs I've ever written, failing gracefully by producing
an informative error message and avoiding undefined behavior is all that
they are expected to do in such a situation. For most of those programs,
it's the only thing that they could do.
It's completely normal for a program to require that it's input files be
changed, if at all, only by the program itself. The overwhelming
majority of the programs I've written, and most of the programs I use,
have precisely that requirement. It is entirely routine and normal to
take the precautions needed to ensure that a program's input files are
not subject to change during the running of the program: we use file
permissions to prevent unauthorized writes. We write scripts which make
sure that the programs which create the input files are complete, before
starting the programs which read them. W set aside working areas, and
count on other users who do have group-write permissions to those
working areas to be polite enough not to exercise those permissions
while we're using those areas.
There's obviously programs that do need to deal with input files that
might change while they are being read. I frequently use mail readers
and version control systems that must be able to deal with such
situations. However I think it's inappropriate to impose such a
requirement on all programs, regardless of their purpose.