Advertisement
1v4n0ff

Untitled

Jul 12th, 2025 (edited)
24
0
23 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.96 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "errors"
  5.     "fmt"
  6.     "io"
  7.     "os"
  8.     "strconv"
  9. )
  10.  
  11. type User struct {
  12.     Name    string
  13.     PostNum int
  14.     Role    int
  15. }
  16.  
  17. func (u *User) Write(buf []byte) (int, error) {
  18.     var seps []int
  19.     fmt.Println("writing") // for simple debug, just be sure that Write is calling, which is not in (1) case (see below)
  20.     for i := range buf {
  21.         if buf[i] == 44 {
  22.             seps = append(seps, i)
  23.         }
  24.     }
  25.     if len(seps) != 2 {
  26.         return 0, fmt.Errorf("user writing error, got %d seps with buf: %v(%s)", len(seps), buf, buf)
  27.     }
  28.     u.Name = string(buf[:seps[0]])
  29.     posts, err := strconv.Atoi(string(buf[seps[0]+1 : seps[1]]))
  30.     if err != nil {
  31.         return seps[0], fmt.Errorf("user writing error in parsing post num: %w", err)
  32.     }
  33.     u.PostNum = posts
  34.     role, err := strconv.Atoi(string(buf[seps[1]+1 : len(buf)-2]))
  35.     if err != nil {
  36.         return seps[1], fmt.Errorf("user writing error in parsing role: %w", err)
  37.     }
  38.     u.Role = role
  39.     return len(buf), nil
  40. }
  41. func (u User) Read(buf []byte) (int, error) {
  42.     s := fmt.Sprintf("%s,%d,%d\r\n", u.Name, u.PostNum, u.Role)
  43.     n := min(len(s), len(buf))
  44.     for i := range n {
  45.         buf[i] = s[i]
  46.     }
  47.     return n, io.EOF
  48. }
  49.  
  50. func main() {
  51.     originalUser := &User{"username", 100, 1}
  52.     f, err := os.Create("user.txt")
  53.     if err != nil {
  54.         fmt.Println(err)
  55.         return
  56.     }
  57.     n, err := io.Copy(f, originalUser)
  58.     if err != nil {
  59.         fmt.Println(err)
  60.         return
  61.     }
  62.     fmt.Println(n, "bytes was writed to file") // file is writed correct
  63.     /*
  64.         (1) now if same file instance will be used in reading with io.Copy(userFromFile, f) - userFromFile will be with zero values
  65.         (2) and if first close that file anf reopen it - userFromFile will be correctly read
  66.     */
  67.     // comment next 5 lines for case (1) and uncomment for case (2)
  68.     f.Close()
  69.     f, err = os.Open("user.txt")
  70.     if err != nil {
  71.         fmt.Println(err)
  72.     }
  73.     userFromFile := &User{}
  74.     n, err = io.Copy(userFromFile, f)
  75.     if err != nil {
  76.         fmt.Println(err)
  77.     }
  78.     fmt.Println(n, userFromFile)
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement