Writing to A NON-Existing File in \"C\"

Dennis G. Rears FSAC drears at ardec.arpa
Fri Apr 8 04:06:38 AEST 1988


Michael Deutsch  writes:

->  I have a "C" program that records the program
->  results into a file, provided that file already
->  exists.  In case the file DOES NOT exist I want
->  the program to function identically but the results
->  should be flushed down the tube, i.e. nowhere, i.e.
->  written to a non-existing file?
->  
->  What sort of "file pointer" or trick should I use
->  to accomplish my goal?

Here is sample code that will allow you to do this. It will exit
if it can't open for appending any file.  If it can not stat the
file it assumes it doesn't exist.  You can be fancy and check errno
though.
----------------------------------------------------------------------

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FILENAME  "/usr/foobar"      /*  not a trademark of AT&T *?
#define NULL	  "/dev/null/"

main(a,b,c)
int a;
char *b[],*c[];

{
	struct stat *buf;
	FILE	*fopen(), *fp, *fr;

	if(!stat(FILE,buf){
		if ( (fp=fopen(NULL,"a")) == NULL ) { 
			/* or use perror() */
			(void)fprintf (stderr, 
				"%s: Can not open /dev/null file\n",b[0]));
			exit(-1);
		}
		else
			if ( (fp=fopen(FILENAME,"a")) == NULL ) { 
				(void)fprintf (stderr, 
				"%s: Can not open %sfile\n",b[0],FILENAME));
				exit(-1);
				
}


Dennis

------------------------------------------------------------
ARPA:		drears at ardec-ac4.arpa
UUCP:   	...!uunet!ardec-ac4.arpa!drears
AT&T:		201-724-6639
Snailmail:	Box 210, Wharton, NJ 07885
Govt Nonmail:	US Army ARDEC, ATTN SMCAR-FSS-E, Dennis Rears
		Bldg 94, Picatinny Arsenal, NJ 07806
Flames:		/dev/null
------------------------------------------------------------



More information about the Comp.unix.wizards mailing list