Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how would i create an output stream in c like stdout?

if printf uses stdout but how would i write a print function using my own output stream? i want to handle this stream with a OO-like structure but i can do that myself. is this possible? this for learning.

would something like this work - i didnt test this code:

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

how would i get printf(char*, ...) print to the console? would i have to read the file in the same function?

like image 372
evolon696 Avatar asked Nov 27 '11 20:11

evolon696


1 Answers

Try use fdopen (see The GNU C Library: Descriptors and Streams).

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

Compile with gcc as below, where 3 is the same as defined in filedes.

gcc -o teststream teststream.c && ./teststream 3> afile.txt && cat afile.txt

The result:

hello, world!
goodbye, world!
like image 82
Daniel Marcos Avatar answered Nov 02 '22 23:11

Daniel Marcos