Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to write input from keyboard into a file in Golang

Tags:

go

I am trying to take input from the keyboard and then store it in a text file but I am a bit confused on how to actually do it.

My current code is as follow at the moment:

// reads the file txt.txt 
bs, err := ioutil.ReadFile("text.txt")
if err != nil {
      panic(err)
}

// Prints out content
textInFile := string(bs)
fmt.Println(textInFile)

// Standard input from keyboard
var userInput string
fmt.Scanln(&userInput)

//Now I want to write input back to file text.txt
//func WriteFile(filename string, data []byte, perm os.FileMode) error

inputData := make([]byte, len(userInput))

err := ioutil.WriteFile("text.txt", inputData, )

There are so many functions in the "os" and "io" packages. I am very confused about which one I actually should use for this purpose.

I am also confused about what the third argument in the WriteFile function should be. In the documentation is says of type " perm os.FileMode" but since I am new to programming and Go I am a bit clueless.

Does anybody have any tips on how to proced? Thanks in advance, Marie

like image 217
miner Avatar asked Sep 13 '12 15:09

miner


People also ask

How do I write to a file in Golang?

To write to files in Go, we use the os , ioutil , and fmt packages. The functions that we use typically return the number of bytes written and an error, if any. We use Go version 1.18.

How do I read and write files in Golang?

Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file.

What is standard input in Golang?

Standard input, often abbreviated stdin, is a stream from which a program reads its input data. To read input from users in Go, we use the fmt , bufio , and os packages. $ go version go version go1.18.1 linux/amd64. We use Go version 1.18.


1 Answers

// reads the file txt.txt 
bs, err := ioutil.ReadFile("text.txt")
if err != nil { //may want logic to create the file if it doesn't exist
      panic(err)
}

var userInput []string

var err error = nil
var n int
//read in multiple lines from user input
//until user enters the EOF char
for ln := ""; err == nil; n, err = fmt.Scanln(ln) {
    if n > 0 {  //we actually read something into the string
        userInput = append(userInput, ln)
    } //if we didn't read anything, err is probably set
}

//open the file to append to it
//0666 corresponds to unix perms rw-rw-rw-,
//which means anyone can read or write it
out, err := os.OpenFile("text.txt", os.O_APPEND, 0666)
defer out.Close() //we'll close this file as we leave scope, no matter what

if err != nil { //assuming the file didn't somehow break
    //write each of the user input lines followed by a newline
    for _, outLn := range userInput {
        io.WriteString(out, outLn+"\n")
    }
}

I've made sure this compiles and runs on play.golang.org, but I'm not at my dev machine, so I can't verify that it's interacting with Stdin and the file entirely correctly. This should get you started though.

like image 67
matthias Avatar answered Sep 24 '22 05:09

matthias