Go入门笔记34-Go 使用Ioctl

Go获取控制台宽度
1、代码

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.Println(width)
}

2、运行结果
Go入门笔记34-Go 使用Ioctl

上一篇:go语言游戏服务端开发(三)——服务机制


下一篇:Endian