如果 printf 使用标准输出,但我如何使用自己的输出流编写打印函数?我想用类似 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;
}
我如何将 printf(char*, ...) 打印到控制台?我必须用相同的函数读取文件吗?
最佳答案
尝试使用 fdopen
(参见 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;
}
用 gcc 编译如下,其中 3
与 filedes
中定义的相同。
gcc -o teststream teststream.c && ./teststream 3> afile.txt && cat afile.txt
结果:
hello, world!
goodbye, world!
关于c - 我将如何像标准输出一样在 c 中创建文件输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288906/