fopen() and memory shortage

Peter da Silva peter at ficc.uu.net
Wed Feb 7 04:51:29 AEST 1990


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. <peter @ ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'

-- 



More information about the Comp.lang.c mailing list