Q:

Golang program to read data from file word by word using the 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 file word by word 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 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 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 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 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.

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 create an empty zip file... >>
<< Golang program to read data line by line from file...