Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "errors"
- "fmt"
- "io"
- "os"
- "strconv"
- )
- type User struct {
- Name string
- PostNum int
- Role int
- }
- func (u *User) Write(buf []byte) (int, error) {
- var seps []int
- fmt.Println("writing") // for simple debug, just be sure that Write is calling, which is not in (1) case (see below)
- for i := range buf {
- if buf[i] == 44 {
- seps = append(seps, i)
- }
- }
- if len(seps) != 2 {
- return 0, fmt.Errorf("user writing error, got %d seps with buf: %v(%s)", len(seps), buf, buf)
- }
- u.Name = string(buf[:seps[0]])
- posts, err := strconv.Atoi(string(buf[seps[0]+1 : seps[1]]))
- if err != nil {
- return seps[0], fmt.Errorf("user writing error in parsing post num: %w", err)
- }
- u.PostNum = posts
- role, err := strconv.Atoi(string(buf[seps[1]+1 : len(buf)-2]))
- if err != nil {
- return seps[1], fmt.Errorf("user writing error in parsing role: %w", err)
- }
- u.Role = role
- return len(buf), nil
- }
- func (u User) Read(buf []byte) (int, error) {
- s := fmt.Sprintf("%s,%d,%d\r\n", u.Name, u.PostNum, u.Role)
- n := min(len(s), len(buf))
- for i := range n {
- buf[i] = s[i]
- }
- return n, io.EOF
- }
- func main() {
- originalUser := &User{"username", 100, 1}
- f, err := os.Create("user.txt")
- if err != nil {
- fmt.Println(err)
- return
- }
- n, err := io.Copy(f, originalUser)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println(n, "bytes was writed to file") // file is writed correct
- /*
- (1) now if same file instance will be used in reading with io.Copy(userFromFile, f) - userFromFile will be with zero values
- (2) and if first close that file anf reopen it - userFromFile will be correctly read
- */
- // comment next 5 lines for case (1) and uncomment for case (2)
- f.Close()
- f, err = os.Open("user.txt")
- if err != nil {
- fmt.Println(err)
- }
- userFromFile := &User{}
- n, err = io.Copy(userFromFile, f)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Println(n, userFromFile)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement