fprintf/variable args question

A

Andrew Fabbro

I have code with stuff like this all over it:

sprintf(errmsg,"somefunc(): %s has illegal character
%c",somestring,somechar);
fatal_error(errmsg);

where fatal_error() just fprintf's to stderr and exits. I'd like to
change the above to something like:

fatal_error("somefunc(): %s has illegal character
%c",somestring,somechar);

to get rid of the sprintf, errmsg variable, etc.

However, in fatal_error, would I have to redo all the work of fprintf
(the parsing of the format and the variables)? If fatal_error's
prototype looks like this:

void fatal_error (const char *format, ...);

is there an easy way to pass the args to fprintf()? So I could do
something like this:

void fatal_error (const char *format, ...) {
fprintf(stderr, format, <some magic to send all the args>);
exit (1);
}

? I realize the code for fprintf is pretty easily available and I
could just copy it, but that doesn't seem right.

Thanks,

-Drew
 
E

Eric Sosman

Andrew said:
I have code with stuff like this all over it:

sprintf(errmsg,"somefunc(): %s has illegal character
%c",somestring,somechar);
fatal_error(errmsg);

where fatal_error() just fprintf's to stderr and exits. I'd like to
change the above to something like:

fatal_error("somefunc(): %s has illegal character
%c",somestring,somechar);

to get rid of the sprintf, errmsg variable, etc.

However, in fatal_error, would I have to redo all the work of fprintf
(the parsing of the format and the variables)? If fatal_error's
prototype looks like this:

void fatal_error (const char *format, ...);

is there an easy way to pass the args to fprintf()? [...]

No. Use vfprintf() instead.
 
A

Andrey Tarasevich

Andrew said:
...
is there an easy way to pass the args to fprintf()? So I could do
something like this:

void fatal_error (const char *format, ...) {
fprintf(stderr, format, <some magic to send all the args>);
exit (1);
}

? I realize the code for fprintf is pretty easily available and I
could just copy it, but that doesn't seem right.
...

void fatal_error (const char *format, ...) {
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit (1);
}

Note the use of 'vfprintf' instead of 'fprintf'.
 
A

Andrew Fabbro

I was embarassed to find the answer in FAQ answer 15.5.

I will now go to my room without supper.

-Drew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top