Created
          December 29, 2018 01:14 
        
      - 
      
- 
        Save miguelmota/4ac6c2c127b6853593808d9d3bba067f to your computer and use it in GitHub Desktop. 
    Golang file descriptor opening and closing example
  
        
  
    
      This file contains hidden or 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" | |
| "log" | |
| "os" | |
| "syscall" | |
| ) | |
| func main() { | |
| f, err := os.OpenFile("test.txt", os.O_RDONLY, 0755) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fd := f.Fd() | |
| fmt.Println(fd) // 3 | |
| file := os.NewFile(uintptr(fd), "test file") | |
| data := make([]byte, 4) | |
| var dataAt int64 = 2 | |
| n, err := file.ReadAt(data, dataAt) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Println(n) // 4 | |
| fmt.Println(string(data)) // BBCC | |
| if err := syscall.Close(int(fd)); err != nil { | |
| log.Fatal(err) | |
| } | |
| } | 
  
    
      This file contains hidden or 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
    
  
  
    
  | AABBCCDD | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment