Home »
Golang »
Golang Programs
Golang program to read data from file word by word using the scanner
Here, we are going to learn how to read data from file word by word using the scanner in Golang (Go Language)?
Submitted by Nidhi, on April 09, 2021 [Last updated : March 04, 2023]
How to read data from file word by word using the scanner in Golang?
Problem Solution:
In this program, we will open an existing file and create a scanner object using a file pointer and then read data from file word by word and print on the console screen.
Program/Source Code:
The source code to read data from file word by word using the scanner is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Golang code to read data from file word by word using the scanner
// Golang program to read data from file
// word by word using the scanner
package main
import "os"
import "fmt"
import "bufio"
func main() {
filePtr, err := os.Open("Demo.txt")
if err != nil {
fmt.Println(err)
}
myScanner := bufio.NewScanner(filePtr)
myScanner.Split(bufio.ScanWords)
result := myScanner.Scan()
if result == false {
err = myScanner.Err()
if err == nil {
fmt.Println("Reached to the end of file")
} else {
fmt.Println(err)
}
}
fmt.Printf("Word1: %s\n", myScanner.Text())
result = myScanner.Scan()
if result == false {
err = myScanner.Err()
if err == nil {
fmt.Println("Reached to the end of file")
} else {
fmt.Println(err)
}
}
fmt.Printf("Word2: %s\n", myScanner.Text())
}
Output:
Word1: Hello
Word2: World
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt, os packages then we can use a function related to the fmt and os package.
Here, we also imported the bufio package to use the scanner to read data from the file.
In the main() function, we opened the "Demo.txt" file and then created a scanner object using bufio.NewScanner() function and then we used the Split() function to read data word by word. After that, we can read data word by word using the Scan() and Text() function and print the result on the console screen.
Golang File Handling Programs »