Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FPRINF question

Status
Not open for further replies.

TanyaB

Programmer
Aug 15, 2001
18
IL
I've got the program that send many error messages to some output file using fprintf; I need to change file with stderr according to value of some environmetal variable;
the problem that I have MANY fprintf's in code, and I don't want every time do :if (strcmp(getenv("SOME_ENV_VAR"),"Some value")== 0) then fprintf(stderr....
else
fprintf(fp....

How can I do it once ?
Can I somehow point to stderr ?
 
I'm presuming that you only open the file that you refer to in your fprintf() statements once and then use the resulting file pointer in your fprintf() calls.

If this is so you should be able to make a decision based on your environment variable at that stage (ie only once) by using your current fopen() call if the environment variable is not set.

If the environment variable IS and you want to use stderr then you need to open stderr using the open() call. This will return a numeric file handle (usually 2, stdin is 0, stdout is 1 and stderr is 2). You can then convert the returned file handle into a FILE * by using the fdopen (or _fdopen depending on your compiler) call.

Depending on your compiler you may be able to open stderr directly in your fopen() call using STDERR as the file name - refer to your compiler and/or library documentation.

Cheers - Gavin
 
I'm presuming that you only open the file that you refer to in your fprintf() statements once and then use the resulting file pointer in your fprintf() calls.

If this is so you should be able to make a decision based on your environment variable at that stage (ie only once) by using your current fopen() call if the environment variable is not set.

If the environment variable IS set and you want to use stderr then you need to open stderr using the open() call. This will return a numeric file handle (usually 2, stdin is 0, stdout is 1 and stderr is 2). You can then convert the returned file handle into a FILE * by using the fdopen (or _fdopen depending on your compiler) call.

Depending on your compiler you may be able to open stderr directly in your fopen() call using STDERR as the file name - refer to your compiler and/or library documentation.

Cheers - Gavin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top