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 .