我将如何在像stdout这样的c中创建输出流?

evo*_*696 5 c io streaming stdout stream

如果printf使用stdout,但我如何使用自己的输出流编写打印功能?我想用类似OO的结构处理这个流,但我可以自己做.这可能吗?这是为了学习.

会像这样的工作 - 我没有测试这段代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

FILE* stdout2 = NULL;

int init() {
    stdout2 = fopen("stdout.txt", "w");
    if (!stdout2) return -1;
    return 1;
}

void print(char* fmt, ...) {
    va_list fmt_args;
    va_start(fmt_args, fmt);
    char buffer[300];
    vsprintf(buffer, fmt, fmt_args);
    fprintf(stdout2, buffer);
    fflush(stdout2);
}

void close() {
    fclose(stdout2);
}

int main(int argc, char** argv) {
    init();
    print("hi"); // to console?
    close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我如何将printf(char*,...)打印到控制台?我必须在同一个函数中读取文件吗?

小智 6

尝试使用fdopen(请参阅GNU C库:描述符和流).

#include <stdio.h>

int main(void) {

  int filedes = 3; // New descriptor
  FILE *stream = fdopen (filedes, "w");
  fprintf (stream, "hello, world!\n");
  fprintf (stream, "goodbye, world!\n");
  fclose (stream);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

用gcc编译如下,其中3与中定义的相同filedes.

gcc -o teststream teststream.c && ./teststream 3> afile.txt && cat afile.txt
Run Code Online (Sandbox Code Playgroud)

结果:

hello, world!
goodbye, world!
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以使用fprintf写入 FILE* ,它具有与 printf 相同的语义。

int main(int argc, char** argv) {
    init();
    fprintf(stdout2,"hi"); // will print to file
    close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)