Q:

Golang program to read data line by line from file using scanner

belongs to collection: Golang File Handling Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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 fmtos 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to read data from file word by word... >>
<< Golang program to get the size of the file using S...