Golang : Text file editor (accept input from screen and save to file)
The images of me learning WordStar as kid somehow appeared in my dream yesterday. So, today I'm going to write this tutorial to mimic a simple text editor and also to demonstrate how to accept input from screen and save each input line directory into a file.
The code below will accept text input from each line and save it to a text file. To exit the program and save the file, you need to go to a new line and enter a dot/period ( . )
scrinputtofile.go
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
fname := "data.txt"
// print text file
textin, err := ioutil.ReadFile(fname)
if err == nil {
fmt.Println(string(textin))
}
var userInput []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if line == "." {
break // to stop writing enter . (period) and press enter
}
userInput = append(userInput, line+"\n")
}
// append text to file
// 0666 means everyone can read and write but not execute
f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
defer f.Close()
if err == nil {
fmt.Println("Saving to file and exit program")
for _, eachLine := range userInput {
io.WriteString(f, eachLine)
}
}
// print text file
textin, err = ioutil.ReadFile(fname)
if err != nil {
panic(err)
}
fmt.Printf("%s content : \n ", fname)
fmt.Println(string(textin))
}
Sample output :
./scrinputtofile
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
this is line 6
你好吗(how are you) ?
.
Saving to file
text.txt content :
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
this is line 6
你好吗(how are you) ?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+15.6k Golang : Update database with GORM example
+39.7k Golang : Convert to io.ReadSeeker type
+50.5k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+51.6k Golang : How to get time in milliseconds?
+10k Golang : Embed secret text string into binary(executable) file
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+12k Golang : Encrypt and decrypt data with x509 crypto
+4.8k Linux : How to set root password in Linux Mint
+12.4k Golang : zlib compress file example
+20.5k Golang : Underscore or snake_case to camel case example
+12.3k Golang : Exit, terminating or aborting a program