4

In C I can read and write files using scanf and printf by piping them as follows:

freopen ("input.txt", "r", stdin);
freopen ("output.txt", "w", stdout);

In Java you can do the same with

System.setIn

And friends.

This it very convenient if you need to swap between using a file and stdin/stdout often, and if to keep your code free from file pointers.

Does Go have something similar?

fuz
  • 88,405
  • 25
  • 200
  • 352
Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114

1 Answers1

7

You can assign to os.Stdin, os.Stdout, and os.Stderr.

import "os"

os.Stdin, err = os.OpenFile("input.txt",
    os.RDONLY | os.O_CREATE, 0666)
os.Stdout, err = os.OpenFile("output.txt",
    os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0666)
fuz
  • 88,405
  • 25
  • 200
  • 352
  • I get `undefined: os.O_TRUNCATE`, but otherwise it works like a charm! Thanks! – Thomas Ahle Jun 30 '14 at 13:44
  • 1
    @Use os.O_TRUNC instead. – fuz Jun 30 '14 at 13:45
  • It's interesting that I must specify all these parameters. Are the ones you have specified specific for stdout? – Thomas Ahle Jun 30 '14 at 17:37
  • 1
    @ThomasAhle The parameters I specified generate a file in the same way your freopen() call would do. (opening the file as write-only, creating it if neccessary, truncating it if it already exists). You could specify other flags if you want more complex behavior, the os.Open() function is just a shorthand for the common case of opening an existing file as read-only (same as with "r" in C). – fuz Jun 30 '14 at 18:19
  • Is 0666 also the same permissions that freopen uses? – Thomas Ahle Jun 30 '14 at 19:13
  • 1
    @ThomasAhle 0666 means read and write permission for everyone. The umask is applied to this permission by the operating system, usually stripping write permissions for others. This is the permission freopen() uses, too. – fuz Jun 30 '14 at 20:54
  • 1
    @ThomasAle I update my answer again, as os.Open() is not quite equal to what freopen does. You might want to check the docs for more details. – fuz Jun 30 '14 at 20:56
  • I came to think of how this is in terms of speed? Will the input streams be buffered? – Thomas Ahle Jul 06 '14 at 17:58
  • @ThomasAhle No. They aren't normally buffered anyway normally. If you want to have buffered IO, use a [bufio.Reader](http://golang.org/pkg/bufio/#Reader) or a [bufio.Writer](http://golang.org/pkg/bufio/#Writer) – fuz Jul 06 '14 at 21:29