Example: ReadAll, ReadDir, and ReadFile from IO Package
ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF.
ReadDir reads the directory named by dirname and returns a list of directory entries sorted by filename.
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF.
***** Create a text file input.txt and write the content which you want to read in same directory in which you will run below program *****
Example
package main
import (
"io/ioutil"
"log"
"fmt"
"os"
)
func exampleReadAll() {
file, err := os.Open("input.txt")
if err != nil {
log.Panicf("failed reading file: %s", err)
}
defer file.Close()
data, err := ioutil.ReadAll(file)
fmt.Printf("\nLength: %d bytes", len(data))
fmt.Printf("\nData: %s", data)
fmt.Printf("\nError: %v", err)
}
func exampleReadDir() {
entries, err := ioutil.ReadDir(".")
if err != nil {
log.Panicf("failed reading directory: %s", err)
}
fmt.Printf("\nNumber of files in current directory: %d", len(entries))
fmt.Printf("\nError: %v", err)
}
func exampleReadFile() {
data, err := ioutil.ReadFile("input.txt")
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\nLength: %d bytes", len(data))
fmt.Printf("\nData: %s", data)
fmt.Printf("\nError: %v", err)
}
func main() {
fmt.Printf("########Demo of ReadAll function#########\n")
exampleReadAll()
fmt.Printf("\n\n########Demo of ReadDir function#########\n")
exampleReadDir()
fmt.Printf("\n\n########Demo of ReadFile function#########\n")
exampleReadFile()
}
Output
########Demo of ReadAll function#########
Length: 15 bytes
Data: Golang Programs
Error:
########Demo of ReadDir function#########
Number of files in current directory: 14
Error:
########Demo of ReadFile function#########
Length: 15 bytes
Data: Golang Programs
Error:
Most Helpful This Week
How To Make an HTTP Server in Golang?
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Golang Program to print numbers with diamond pattern
Print inverted full pyramid using star
GO Program to Check Armstrong Number
Golang program to demonstrates how to encode map data into a JSON string.