c - 在 1 行中将字符串发送到标准输出和套接字的方法

标签 c linux unix stdout

我只想将其写入 1 行:

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

所以我想将相同的字符串发送到标准输出和我打开的套接字。我该怎么做?

最佳答案

#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;
}

可以

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

关于c - 在 1 行中将字符串发送到标准输出和套接字的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2123299/

相关文章:

linux - 从内核模块与驱动程序通信

c - c语言fopen隐藏文件

Linux:根据匹配从文本文件中提取指定行数

file - 将包含目录的 SVN 修改文件复制到另一个目录

c++ - 在调用者内部扩展被调用者的指导原则是什么(内联-编译器优化)

c - 通过Winsock发送字符串到HDFS

c++ - Linux 相当于 WaitCommEvent

php - Zend 工具包含路径

c - 指针 - 段错误(核心已转储)

c - 组合两个 _Generic 时出现错误