[英]Redirecting program output in C, use fprintf or "more widely used" solution?
Noob Q, best-practices related: Noob Q,最佳实践相关:
I'm writing a MS BASIC interpreter for macOS using yacc/lex/C.我正在使用 yacc/lex/C 为 macOS 编写 MS BASIC 解释器。 It uses
scanf
/ printf
for PRINT
and INPUT
.它对
PRINT
和INPUT
使用scanf
/ printf
。 I would like to add a CLI option to redirect those to files.我想添加一个 CLI 选项来将它们重定向到文件。
I know how to do this technically, using fopen/fclose and fprintf etc.. But is that how "real" Unixen programs would do it?我知道如何在技术上做到这一点,使用 fopen/fclose 和 fprintf 等。但是“真正的”Unixen 程序会这样做吗? I would like to be as standard as possible to avoid confusion when someone else examines the code.
当其他人检查代码时,我希望尽可能地标准以避免混淆。
On generic Unix/Linux/FBSD, would you...在通用的 Unix/Linux/FBSD 上,你会...
printf
with fprintf(fp,
and default fp
to stdout?printf
与fprintf(fp,
和默认fp
到stdout?printf
s but redirect stdout
?printf
s 但重定向stdout
?(For a general program) (对于一般程序)
There's nothing wrong with simply relying on normal redirection by the parent (like the shell), but if your want to provide a parameter for that (which is also perfectly fine).简单地依赖父级(如 shell)的正常重定向并没有错,但是如果您想为此提供一个参数(这也很好)。
As for using printf
or fprintf
, I don't see much difference.至于使用
printf
或fprintf
,我看不出太大区别。 I would probably choose one or other depending on the typical case.我可能会根据典型情况选择一种或另一种。 If it was almost always output on stdout, would probably use printf and fprintf otherwise.
如果它几乎总是在 stdout 上输出,则可能会使用 printf 和 fprintf 否则。 The part that may be confusing is that another person reading your code may not realize that
printf
isn't the program standard output (as for the redirection, you can use freopen
or -before using stdio- dup2(, 1);
).可能令人困惑的部分是阅读您代码的另一个人可能没有意识到
printf
不是程序标准输出(至于重定向,您可以使用freopen
或 -before 使用 stdio- dup2(, 1);
)。
(For your BASIC interpreter) (对于您的 BASIC 口译员)
In this case, as you are translating INPUT
and PRINT
, scanf
and printf
seem the logical choices, and I'm not sure why you would need an option to change them to something else.在这种情况下,当您翻译
INPUT
和PRINT
, scanf
和printf
似乎是合乎逻辑的选择,我不确定为什么您需要一个选项来将它们更改为其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.