# Go Cheatsheet - Read & Write File

## Read & Write File

### Read File content

1, Use `ioutil.ReadFile`:

```go
content, err := ioutil.ReadFile("sample.txt")
```

2, Open file first (in read-only mode), then `ioutil.ReadAll`

```go
f, err := os.Open("./main.go")
//or open in a different mode: 
// f, err := os.OpenFile("./main.go", os.O_RDWR, os.ModePerm)
content, err := ioutil.ReadAll(f)
```

3, Open file first, then read line by line

Use `bufio.NewScanner`:

```go
sc := bufio.NewScanner(f)
for sc.Scan() {
	fmt.Println(sc.Text())
}
```

Use `bufio.NewReader`:
```go
rd := bufio.NewReader(f)
for {
	ln, err := rd.ReadString('\n')
	if err != nil {
		if err == io.EOF {
			break
		}
		log.Fatalln("Failed to read file", err)
	}
	fmt.Print(ln)
}
```

### Write to File

1, Dump whole content to a file:

```go
ioutil.WriteFile("outf.txt", []byte("hello world"), os.ModePerm)
```

2, Create a new file then write (existing content will be truncated)

```go
outf, err := os.Create("outf.txt")
defer outf.Close()
if err != nil {
	log.Fatalln("Failed to create file.", err)
}
outf.WriteString("hello world\n")
```

3, Append content to file:

```go
outf, err = os.OpenFile(
	"outf.txt",
	os.O_WRONLY|os.O_APPEND|os.O_CREATE, // open file in append mode
	os.ModePerm,
)
defer outf.Close()
if err != nil {
	log.Fatalln("Failed to open file", err)
}
outf.WriteString("append line\n")
```

