开发者

way to send strings to stdout AND socket in 1 line

开发者 https://www.devze.com 2022-12-17 02:51 出处:网络
I want to write this to only 开发者_如何学JAVA1 line: fprintf(stdout, \"RCPT TO: <%s>\\r\\n\", argv[argc-1]);

I want to write this to only 开发者_如何学JAVA1 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?


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]);


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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消