So I'm trying to get my little program to output to a plain text file. I've been successful with Python, C, C++ and C#, but I can't seem to find any documentation on outputting data to a plain text file with Go. Here's my code:
package main
import "fmt"
import "strconv"
func main() {
var age string
fmt.Print("
Welcome to Survey! What is your age?
")
fmt.Scanf("%s", &age)
if _, err := strconv.ParseInt(age,10,64); err == nil {
fmt.Printf("
You are %s years old!
", age)
} else {
fmt.Printf("
That's not an age! Try again...
")
}
fmt.Println("
Nice! Now, what is your name?
")
fmt.Printf("Enter your name: ")
var name string
fmt.Scanf("%s", &name)
fmt.Println("
Hello " + name + "! It's nice to meet you!")
fmt.Println("
Would you like to write your age and name to a text file?")
fmt.Println("
Press 1 for yes or any other key for no!
")
var yes int
fmt.Scanf("%d", &yes)
if yes == 1 {
fmt.Printf("
All done! Check Survey.txt in the current directory!
")
} else {
fmt.Printf("
Okay! Exiting...
")
}
}
You can see if the user enters 1, it prints a message to check the current directory for Survey.txt. Basically all I'm trying to do is have Go write the age and name variables to a plain text file called Survey.txt.
Example:
Age: x
Name: x
If anyone has an idea of how to do this, it'd be awesome. My operating system is Xubuntu 16.04.3 LTS, but I don't think that will have much of an impact. The code works fine as is right now, I just want to add that feature. Thanks!
I think it's easy to output to a text file. Simply redirect the program output. On the terminal command line goprogram >> outputFile.txt Anyway, I am only providing a suggestion, you don't have to click minuses, given that no explanation is provided if that is urgent, if it's for academia etc.
You can write to a file using ioutil.WriteFile:
data := fmt.Sprintf("Age: %d
Name: %s
", age, name)
err := ioutil.WriteFile("Survey.txt", []byte(data), 0644)
if err != nil {
log.Fatalf("error writing Survey.txt: %s", err)
}