简体   繁体   中英

Redirecting program output in C, use fprintf or "more widely used" solution?

Noob Q, best-practices related:

I'm writing a MS BASIC interpreter for macOS using yacc/lex/C. It uses scanf / printf for PRINT and INPUT . I would like to add a CLI option to redirect those to files.

I know how to do this technically, using fopen/fclose and fprintf etc.. But is that how "real" Unixen programs would do it? 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...

  1. replace all the printf with fprintf(fp, and default fp to stdout?
  2. keep all the printf s but redirect stdout ?
  3. rely on the shell and piping and not offer this as a CLI option at all?

(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).

As for using printf or fprintf , I don't see much difference. 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. 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); ).

(For your BASIC interpreter)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM