Attempting to enter keyboard input into a file in the Golang

I try to take keyboard input and then save it in a text file, but I'm a bit confused about how to actually do this.

My current code is as follows:

// 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, ) 

The os and io packages have so many features. I am very confused about which I really should use for this purpose.

I am also confused by what should be the third argument to the WriteFile function. The documentation talks about the type "perm os.FileMode", but since I'm new to programming and Go, I'm a little stranger.

Does anyone have any tips on how to proceed? Thanks in advance, Marie

+6
source share
3 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 made sure that this compiles and runs on play.golang.org, but I am not on my dev machine, so I cannot verify that it fully interacts with Stdin and the file. This should help you get started.

+2
source

For instance,

 package main import ( "fmt" "io/ioutil" "os" ) func main() { fname := "text.txt" // print text file textin, err := ioutil.ReadFile(fname) if err == nil { fmt.Println(string(textin)) } // append text to file f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) if err != nil { panic(err) } var textout string fmt.Scanln(&textout) _, err = f.Write([]byte(textout)) if err != nil { panic(err) } f.Close() // print text file textin, err = ioutil.ReadFile(fname) if err != nil { panic(err) } fmt.Println(string(textin)) } 
+3
source

If you just want to add user input to a text file, you can just read how you already did, and use ioutil.WriteFile as you did. So, you already got the right idea.

To make your way, a simplified solution would be the following:

 // Read old text current, err := ioutil.ReadFile("text.txt") // Standard input from keyboard var userInput string fmt.Scanln(&userInput) // Append the new input to the old using builtin `append` newContent := append(current, []byte(userInput)...) // Now write the input back to file text.txt err = ioutil.WriteFile("text.txt", newContent, 0666) 

The last WriteFile parameter is a flag that defines various parameters for files. The higher bits are parameters such as the file type ( os.ModeDir , for example), and the lower bits represent permissions in the form of UNIX permissions ( 0666 , in octal format, denotes the user rw, group rw, others rw). See the documentation for more details.

Now that your code is working, we can improve it. For example, if a file is open instead of opening it twice:

 // Open the file for read and write (O_RDRW), append to it if it has // content, create it if it does not exit, use 0666 for permissions // on creation. file, err := os.OpenFile("text.txt", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) // Close the file when the surrounding function exists defer file.Close() // Read old content current, err := ioutil.ReadAll(file) // Do something with that old content, for example, print it fmt.Println(string(current)) // Standard input from keyboard var userInput string fmt.Scanln(&userInput) // Now write the input back to file text.txt _, err = file.WriteString(userInput) 

The magic here is that you use the os.O_APPEND flag when opening a file that adds file.WriteString() . Please note that you need to close the file after opening it, which we do after the existence of the function using the defer .

+2
source

Source: https://habr.com/ru/post/925335/


All Articles