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
Split a character string based on change of character
How to convert Go struct to JSON?
How to check UPPERCASE characters in a string in Golang?
How to use wildcard or a variable in our URL for complex routing?
Example to handle GET and POST request in Golang
How to include and execute HTML template?