Forked from novalagung/golang-create-read-write-delete-file.go
Created
September 18, 2017 18:10
-
-
Save danteay/37f5aa4e3eef0f9cfabb1882b5461588 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
) | |
var path = "/Users/novalagung/Documents/temp/test.txt" | |
func main() { | |
createFile() | |
writeFile() | |
readFile() | |
deleteFile() | |
} | |
func createFile() { | |
// detect if file exists | |
var _, err = os.Stat(path) | |
// create file if not exists | |
if os.IsNotExist(err) { | |
var file, err = os.Create(path) | |
if isError(err) { return } | |
defer file.Close() | |
} | |
fmt.Println("==> done creating file", path) | |
} | |
func writeFile() { | |
// open file using READ & WRITE permission | |
var file, err = os.OpenFile(path, os.O_RDWR, 0644) | |
if isError(err) { return } | |
defer file.Close() | |
// write some text line-by-line to file | |
_, err = file.WriteString("halo\n") | |
if isError(err) { return } | |
_, err = file.WriteString("mari belajar golang\n") | |
if isError(err) { return } | |
// save changes | |
err = file.Sync() | |
if isError(err) { return } | |
fmt.Println("==> done writing to file") | |
} | |
func readFile() { | |
// re-open file | |
var file, err = os.OpenFile(path, os.O_RDWR, 0644) | |
if isError(err) { return } | |
defer file.Close() | |
// read file | |
var text = make([]byte, 1024) | |
for { | |
n, err := file.Read(text) | |
if err != io.EOF { | |
if isError(err) { break } | |
} | |
if n == 0 { | |
break | |
} | |
} | |
if isError(err) { return } | |
fmt.Println("==> done reading from file") | |
fmt.Println(string(text)) | |
} | |
func deleteFile() { | |
// delete file | |
var err = os.Remove(path) | |
if isError(err) { return } | |
fmt.Println("==> done deleting file") | |
} | |
func isError(err error) bool { | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
return (err != nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment