Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of freopen in Go

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?

like image 692
Thomas Ahle Avatar asked Oct 19 '25 13:10

Thomas Ahle


1 Answers

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)
like image 64
fuz Avatar answered Oct 21 '25 11:10

fuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!