[Techtalk] C programming: question on fopen() parameters

Julie txjulie at austin.rr.com
Wed Oct 8 07:12:49 EST 2003


Berenice Chong wrote:
> I'm writing a test CGI script in C that writes form information into
> a file. There needs to be a file for every form submitted.  My
> problem is using fopen to open a file in another directory.  The file
> name is the script process ID and if I do this, the file gets created
> in the current directory:
> 
> <snip>
> char filename[6];
> sprintf(filename,"%d",(int)getpid()); 
> filepointer=fopen(filename,"w");	
> <snip>
> 
> What's the correct way to write the first parameter in fopen(), so
> that the file appears in a different directory? 

Assuming there is a parameter named "dirname" to the function,
and that you change

	char filename[6];

to

	char	filename[PATH_MAX];

the correct code would be something like

	if (snprintf (filename, sizeof filename, "%s/%d",
			dirname, getpid ()) >= sizeof filename)
		/* do error stuff */

	if (! (filepointer = fopen (filename, "w")))
		/* do more error stuff */

	/* successfully opened filepointer */

Three comments --

1). Always check your return codes/values/whatever.
2). Always check your buffer sizes (never using sprintf,
     strcat, strcpy, etc. without knowing the data will fit)
3). Always comment your code.  Heavily.
-- 
Julianne Frances Haugh             Life is either a daring adventure
txjulie at austin.rr.com                  or nothing at all.
					    -- Helen Keller



More information about the Techtalk mailing list