0

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?

0

3 Answers 3

5

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

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 to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.
1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.