fopen() and memory shortage: summary
Tapani Tarvainen
tarvaine at tukki.jyu.fi
Fri Feb 16 17:54:56 AEST 1990
Thanks to everybody who responded! In case someone is interested,
here's a summary of the responses (attributions omitted, most ideas
were suggested by several people):
Checking for the existence of a file:
* open()/close() are less portable than fopen()/fclose() (the latter are in
ANS, the former in UNIX and lookalikes, including most MS-DOS compilers).
* stat() is probably the easiest if available, however it is no more
portable than open() and close(). (I decided to use
#ifdef MSDOS /* use stat() */ #else /* use fopen()/fclose */ #endif
-- most other systems are likely to have enough and/or virtual memory
anyway).
Ensuring that the original file won't get lost:
* Write to a temporary file first and rename it after success. This is
actually what the program was trying to do, but first it tested if
the file existed to see if this was necessary :-(. This can of course
be done even when the file doesn't exist, obviating this problem.
* Backup can be done safely by simply trying rename() -- if it doesn't
work, then the file probably doesn't exist. The problem here is how
to warn about other possible reasons of failure (write-protected
directory or whatever).
Ensuring the ability to write the file when memory has ran out:
* Unbuffered I/O is unacceptably inefficient.
* Writing my own buffered output routine should work, but rather waste
effort, and doing it in a portable way isn't easy either.
* malloc()ing the required space before hand and free()ing it before
fopen() would probably work, but is rather, eh, yucky.
* Keeping a stream open throughout and using freopen() should work,
and would probably even be quite portable. (This is what I'll
probably do if this really becomes a problem. For now it's
enough for me that the original can no longer be lost.)
* Somebody suggested closing stdin, stdout or stderr to make room.
Unfortunately it doesn't work, as they may be unbuffered.
--
Tapani Tarvainen (tarvaine at jyu.fi, tarvainen at finjyu.bitnet)
More information about the Comp.lang.c
mailing list