[Techtalk] C programming: question on fopen() parameters
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:
> char filename;
> 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
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