Path: utzoo!attcan!uunet!samsung!zaphod.mps.ohio-state.edu!wuarchive!texbell!sugar!ficc!peter From: peter@ficc.uu.net (Peter da Silva) Newsgroups: comp.lang.c Subject: Re: fopen() and memory shortage Message-ID: Date: 6 Feb 90 17:51:29 GMT References: <2935@tukki.jyu.fi> Reply-To: peter@ficc.uu.net (Peter da Silva) Organization: Xenix Support, FICC Lines: 60 If you're using UNIX, the following will work: FILE *safe_fopen(name, mode) char *name, *mode; { static char buffer[BUFSIZ]; FILE *fp; char *s; int i, filepart; /* * The following code creates a new file name in the same * directory as the original. */ filepart = 0; for (i = 0; name[i]; i++) { buffer[i] = name[i]; if (buffer[i] == '/') filepart = i + 1; } strcpy(&buffer[filepart], "tmpXXXXXX"); mktmp(buffer); /* The following code opens the new file. It then attempts * to slide the new file in under the old name, aborting * if anything blows up and closing the new file. */ if (fp = fopen(buffer, mode)) { if (unlink(name)) { fclose(fp); fp = 0; } else { if (link(buffer, name)) { fclose(fp); fp = 0; } unlink(buffer); } } return fp; } This will not have the exact same semantics as fopen. In particular, it will happily overwrite a destination file that you don't have write permission on. If you're root, it will happily delete a directory. As I found out once upon a time with similar code. It would be a good idea to do some more tests. -- _--_|\ Peter da Silva.+ 1 713 274 5180. . / \ \_.--._/ Xenix Support -- it's not just a job, it's an adventure! v "Have you hugged your wolf today?" `-_-' --