Created
December 26, 2017 12:42
-
-
Save yijia2413/b1ebbe5acdb2e57d9d6ecd92bd7bcc68 to your computer and use it in GitHub Desktop.
go read write example
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" | |
"os" | |
"bufio" | |
"io/ioutil" | |
) | |
type Page struct { | |
Title string | |
Body []byte | |
} | |
func (p *Page) save() { | |
title := p.Title | |
outFile, outErr := os.OpenFile(title, os.O_WRONLY|os.O_CREATE, 0666) | |
if outErr != nil { | |
fmt.Println("open/create file error") | |
return | |
} | |
defer outFile.Close() | |
outWritter := bufio.NewWriter(outFile) | |
s := string(p.Body[:]) | |
outWritter.WriteString(s) | |
outWritter.Flush() | |
} | |
func (p *Page) save1() (err error) { | |
return ioutil.WriteFile(p.Title, p.Body, 0666) | |
} | |
func load(title string) { | |
input, err := os.Open(title) | |
if err != nil { | |
fmt.Println("read error") | |
return | |
} | |
fmt.Println(input) | |
} | |
func (p *Page) load1(title string) (err error) { | |
p.Title = title | |
p.Body, err = ioutil.ReadFile(p.Title) | |
return err | |
} | |
func main() { | |
var p *Page = new(Page) | |
p.Title = "hello.csv" | |
p.Body = []byte("hskfjksfhkshfjshckjnhkjdfhj") | |
p.save() | |
load(p.Title) | |
page := Page{ | |
"page.csv", | |
[]byte("huge page ..."), | |
} | |
page.save1() | |
var new_page Page | |
new_page.load1("page.csv") | |
fmt.Println(string(new_page.Body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment