[go]从os.Stdin探究文件类源码

咋一看go的标准输入输出函数有一箩筐. 细究了一下.

- 从标准输入获取输入
fmt.Scan   以空白(空格或换行)分割,值满后无结束
fmt.Scanln 以空格作为分割,遇到换行结束
fmt.Scanf  以空格作为分隔符,回车结束

- 从字符串获取输入
fmt.Sscan
fmt.Sscanln
fmt.Sscanf

- 从文件获取输入
fmt.Fscan
fmt.Fscanln
fmt.Fscanf



- 输出
fmt.Print
fmt.Println
fmt.Printf

- 格式化输出并返回str
fmt.Sprint
fmt.Sprintln
fmt.Sprintf

fmt.Scan使用参考

Go语言标准库之fmt.Scan - aaronthon - 博客园

os.Stdin使用

os.Stdin.Write
os.Stdin.WriteSring
Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
func NewFile(fd uintptr, name string) *File {
	h := syscall.Handle(fd)
	if h == syscall.InvalidHandle {
		return nil
	}
	return newFile(h, name, "file")
}
func newFile(h syscall.Handle, name string, kind string) *File {
	if kind == "file" {
		var m uint32
		if syscall.GetConsoleMode(h, &m) == nil {
			kind = "console"
		}
		if t, err := syscall.GetFileType(h); err == nil && t == syscall.FILE_TYPE_PIPE {
			kind = "pipe"
		}
	}

	f := &File{&file{
		pfd: poll.FD{
			Sysfd:         h,
			IsStream:      true,
			ZeroReadIsEOF: true,
		},
		name: name,
	}}
	runtime.SetFinalizer(f.file, (*file).close)

	// Ignore initialization errors.
	// Assume any problems will show up in later I/O.
	f.pfd.Init(kind, false)

	return f
}
type File struct {
	*file // os specific
}
type file struct {
	pfd        poll.FD
	name       string
	dirinfo    *dirInfo // nil unless directory being read
	appendMode bool     // whether file is opened for appending
}


func (f *File) WriteString(s string) (n int, err error) {
	return f.Write([]byte(s))
}

简化如下

type File struct{
   *file
}


//绑定方法
func(f *File)Write(){

}
func(f *File)WriteString(){

}


//构造方法
func newFile(){
    return &File{}
}

os.Stdin = newFile(xxx)
原文地址:https://www.cnblogs.com/iiiiiher/p/11797280.html