- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to Read the Contents of a File
pre.prettyprint{width:99%!important;} a.demo{top:12px!important; float:right!important;}
To read the contents of a file, we can take following steps −
- We can create a file called test.txt.
- Clean-up using defer statement.
- Write the contents of string.
- Call ReadFile() method to read the file.
- ReadFile reads the file named by filename and returns the contents.
- Print the content of the file.
Example
package main import ( "fmt" "io/ioutil" "log" "os" ) func CreateFile() { file, err := os.Create("test.txt") if err != nil { log.Fatalf("failed creating file: %s", err) } defer file.Close() _, err = file.WriteString("Welcome to Tutorials Point") if err != nil { log.Fatalf("failed writing to file: %s", err) } } func ReadFile() { fileName := "test.txt" data, err := ioutil.ReadFile(fileName) if err != nil { log.Panicf("failed reading data from file: %s", err) } fmt.Printf("\n%s", data) } func main() { CreateFile() ReadFile() }
Output
Welcome to Tutorials Point
Advertisements