Writing to A NON-Existing File in "C"

Barnacle Wes wes at obie.UUCP
Mon Apr 11 16:31:49 AEST 1988


In article <9654 at jplgodo.UUCP> deutsch at jplgodo.UUCP (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?

In article <10285 at steinmetz.steinmetz.ge.com>, davidsen at steinmetz.steinmetz.ge.com (William E. Davidsen Jr) replies:
>   First problem is to open the file if it exists, by
> 	fp = fopen(MYFILE, "r+");	/* open, no create	*/
> 	outflag = fp != NULL;		/* set a flag		*/
> 	if (outflag) fseek(fp, 0L, 2);	/* rewind if open ok	*/
> 
>   You can then print to the file using a macro, such as:
> 	#define cprintf if (outflag) fprintf
> 	.
> 	.
> 	cprintf(fp, "format", data);

I'd do it slightly different.  Unless you need speed, try using
access(2) to determine if the file is available to you, and if not
open /dev/null for writing:

	char *name;
	FILE *ofp;

	if (access("/data/file/name", 02)) 	/* 02 = write access */
		name = "/data/file/name";
	else
		name = "/dev/null";
	ofp = fopen(name, "a");

	...
Then just fprintf all of your data to handle "ofp".  Less efficient in
the no-output case, but it makes the program somewhat easier to read.
-- 
    /\              -  "Against Stupidity,  -    {backbones}!
   /\/\  .    /\    -  The Gods Themselves  -  utah-cs!utah-gr!
  /    \/ \/\/  \   -   Contend in Vain."   -  uplherc!sp7040!
 / U i n T e c h \  -       Schiller        -     obie!wes



More information about the Comp.unix.questions mailing list