Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!umich!samsung!think!mintaka!bloom-beacon!eru!luth!sunic!tut!tukki!tarvaine From: tarvaine@tukki.jyu.fi (Tapani Tarvainen) Newsgroups: comp.lang.c Subject: fopen() and memory shortage: summary Message-ID: <3015@tukki.jyu.fi> Date: 16 Feb 90 06:54:56 GMT Reply-To: tarvaine@tukki.jyu.fi (Tapani Tarvainen) Organization: University of Jyvaskyla, Finland Lines: 47 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@jyu.fi, tarvainen@finjyu.bitnet)