3

I can see two ways to fill an empty file with data:

$ run_program arg1 > data_file

or, specifically write code that manages a file and write to it? ie. a file stream?

Which is better to implement?

  • Hope it is specific enough. If it isn't, just say. – user2738698 Mar 27 '14 at 14:06
6

If you already have access to a convenient way of redirecting data to a file, e.g. UNIX's > operator, then it makes absolutely no sense to hard-code file-opening and writing logic into your program.

Even if you always want to create a specific file, you can just create a script, alias or function that knows the filename and does the right thing, while leaving other users of the program free to whatever they want with their output program. Also, your program gets smaller and less complicated, which is always good.

In short: writing to STDOUT can easily be extended to writing to a file. Using open(), write() and close() syscalls cannot easily be extended to piping, paging, ignoring, using on a read-only or full file system, etc.

  • +1 This, so much. Some of the most commonly-used Unix utilities like grep and sed are useful because they transform streams. – Doval Mar 27 '14 at 15:15
  • 1
    I find a lot of the core utils and other commandline software do both, where it by default writes to stdout but provides a parameter to redirect, same with stdin vs input files. – whatsisname Mar 27 '14 at 15:40
2

In a strict sense, the Unix tradition would dictate to only deal with input and output streams and not duplicate the functionality of writing to files that is already present in the shell.

But of course, almost all real-world Unix utilities do have options for writing to and reading from files. And it's pretty darn convenient that they do! (Plus, not everybody works in a Unix environment.)

1

I always like programs that offer a -o option to specify the output file. It does not mean I never use redirection but there are times where I am not so sure about how the current command line handles the pipe and redirection, it's great to have -o option. Here is an example I am talking about:

cat thelist | xargs -I_ myprog -i _ -o _.result

Without the -o option, I am not sure how to output to individual files with xargs. Beside, the coding is really not that tricky:

auto outf = stdout;
if (outputFilename) outf = fopen(outputFilename, "w");
// use outf for output
fprintf(outf, "blabla");
// end of using outf
if (outf != stdout) fclose(outf);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.