这个方法是在github.com/rakyll/pb的程序中发现的,闲话少说,直接贴代码:
package main import ( "fmt" "runtime" "syscall" "unsafe" ) const ( TIOCGWINSZ = 0x5413 TIOCGWINSZ_OSX = 1074295912 ) type window struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } func terminalWidth() (int, error) { w := new(window) tio := syscall.TIOCGWINSZ if runtime.GOOS == "darwin" { tio = TIOCGWINSZ_OSX } res, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(syscall.Stdin), uintptr(tio), uintptr(unsafe.Pointer(w)), ) if int(res) == -1 { return 0, err } return int(w.Col), nil } func main() { width, _ := terminalWidth() fmt.Print(width) }