Home »
Golang »
Golang Programs
Golang program to read data line by line from file using scanner
Here, we are going to learn how to read data line by line from file using scanner in Golang (Go Language)?
Submitted by Nidhi, on April 09, 2021 [Last updated : March 04, 2023]
How to read data line by line from file using 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 a file line by line and print on the console screen.
Program/Source Code:
The source code to read data line by line from the file 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 line by line from file using scanner
// Golang program to read data by line by line
// from a file 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)
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("Line1: %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("Line2: %s\n", myScanner.Text())
}
Output:
Line1: Hello World
Line2: Hello India
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 check data is available in file using Scan() function and read data line by line from file using Text() function. If we want to read data using a scanner then it is required to call the Scan() function before the Text() function.
Golang File Handling Programs »