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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With