Getting errno after a write operation

I have the following Go code that will eventually fill up the disk and fail with ENOSPC (just a proof of concept). How can I determine from err returned by os.Write that it really failed due to ENOSPC (so I need a way to capture errno after the write operation)?

 package main import ( "log" "os" ) func main() { fd, _ := os.Create("dump.txt") defer fd.Close() for { buf := make([]byte, 1024) _, err := fd.Write(buf) if err != nil { log.Fatalf("%T %v", err, err) } } } 

EDIT : updated program suggested by @FUZxxl:

 package main import ( "log" "os" "syscall" ) func main() { fd, _ := os.Create("dump.txt") defer fd.Close() for { buf := make([]byte, 1024) _, err := fd.Write(buf) if err != nil { log.Printf("%T %v\n", err, err) errno, ok := err.(syscall.Errno) if ok { log.Println("type assert ok") if errno == syscall.ENOSPC { log.Println("got ENOSPC") } } else { log.Println("type assert not ok") } break } } } 

However, I do not get the expected result. Here is the result:

 2015/02/15 10:13:27 *os.PathError write dump.txt: no space left on device 2015/02/15 10:13:27 type assert not ok 
+6
source share
1 answer

File operations usually return *os.PathError ; cast err to os.PathError and use the err field to examine the root cause, for example:

 patherr, ok := err.(*os.PathError) if ok && patherr.Err == syscall.ENOSPC { log.Println("Out of disk space!") } 
+4
source

Source: https://habr.com/ru/post/982496/


All Articles