tags:

views:

110

answers:

3

I want to write this to only 1 line:

fprintf(stdout, "RCPT TO: <%s>\r\n", argv[argc-1]);
fprintf(sockfd, "RCPT TO: <%s>\r\n", argv[argc-1]);

so i want to send the same string to stdout and to my open socket. How can I do this?

+1  A: 

Not unless you want to write your own function that takes two File* and varargs, and calls fprintf twice.

Paul Tomblin
+6  A: 

With

#include <stdarg.h>

int fprintf_both(FILE *a, FILE *b, const char *fmt, ...)
{
  FILE *f[2];
  const int n = sizeof(f) / sizeof(f[0]);
  int i;
  int sum = 0;

  f[0] = a;
  f[1] = b;

  for (i = 0; i < n; i++) {
    va_list ap;
    int bytes;

    va_start(ap, fmt);
    bytes = vfprintf(f[i], fmt, ap);
    va_end(ap);

    if (bytes < 0)
      return bytes;
    else
      sum += bytes;
  }

  return sum;
}

you can

fprintf_both(stdout, sockfd, "RCPT TO: <%s>\r\n", argv[argc-1]);
Greg Bacon
Bug: you should restart ap after passing it to vfprintf() the first time. You may get away with not doing so, but the standard is explicit (7.15): The object ap may be passed as an argument toanother function; if that function invokes the va_arg macro with parameter ap, thevalue of ap in the calling function is indeterminate and shall be passed to the va_endmacro prior to any further reference to ap.
Jonathan Leffler
Thanks, @Steve and Jonathan! Answer updated.
Greg Bacon
A: 

I guess you want to do this to put it inside something like a while loop condition? You might like the C comma operator, e.g.

while ( f1(), f2() ) { //bla }

The comma causes f1() to be executed, it's return value discarded, followed by f2() and the its return value kept. (i.e. f2() should return an int or bool and f1() doesn't matter)

abc