尝试将键盘输入写入Golang中的文件

min*_*ner 7 go

我试图从键盘输入,然后将其存储在文本文件中,但我对如何实际操作有点困惑.

我目前的代码如下:

// 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, )
Run Code Online (Sandbox Code Playgroud)

"os"和"io"包中有很多功能.我真的很困惑我实际应该为此目的使用哪一个.

我也很困惑WriteFile函数中的第三个参数应该是什么.在文档中说"perm os.FileMode"类型,但由于我是编程和Go的新手,我有点无能为力.

有没有人有关于如何程序的任何提示?玛丽,提前谢谢

mat*_*ias 3

// 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经确保它可以在 play.golang.org 上编译并运行,但我不在我的开发机器上,所以我无法验证它是否完全正确地与 Stdin 和文件进行交互。不过,这应该可以帮助您开始。