0

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 printfs but redirect stdout?
  3. rely on the shell and piping and not offer this as a CLI option at all?
Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98
  • I would personally go with the third option, unless you expect this program to run as a daemon, then it may be beneficial to write to a log file instead of standard output. – smac89 Oct 03 '20 at 21:55

1 Answers1

1

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

Ángel
  • 890
  • 7
  • 12
  • Ok I'll add both options. The reason for redicting PRINT and INPUT is so that you can INPUT from a pre-created file of inputs so every run is identical - for testing and benching purposes. – Maury Markowitz Oct 04 '20 at 15:27