golang读写文件之Scan和Fprintf
1. 标准输入输出
os提供了标准输入输出:
Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
func NewFile(fd uintptr, name string) *File
2. Scan
从键盘和标准输入os.Stdin读取输入,最简单的方法是使用fmt包提供的Scan和Sscan开头的函数。
func Scan(a ...interface{}) (n int, err error) func Scanf(format string, a ...interface{}) (n int, err error) func Scanln(a ...interface{}) (n int, err error) func Sscan(str string, a ...interface{}) (n int, err error) func Sscanf(str string, format string, a ...interface{}) (n int, err error) func Sscanln(str string, a ...interface{}) (n int, err error) func Fscan(r io.Reader, a ...interface{}) (n int, err error) func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
Scanln 扫描来自标准输入的文本,将空格分隔的值依次存放到后续的参数内,直到碰到换行。
Scanf的第一个参数是格式串,其他都相同。
Sscan及开头的函数输入变成了string,Fscan及开头的函数输入变成了io.Reader。
Scan, Fscan, Sscan treat newlines in the input as spaces.
Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.
fmt.Println("Please enter your full name: ") fmt.Scanln(&firstName, &lastName) fmt.Printf("Hi %s %s!\n", firstName, lastName) fmt.Sscanf("30.0 * 25 * hello", "%f * %d * %s", &f, &i, &s) fmt.Println("From the string we read: ", f, i, s) fmt.Println("Please enter string: ") fmt.Scan(&s) fmt.Println(s)
3. Fprintf
printf相关:
func Fprint(w io.Writer, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
通过Fprintln()写文件
const name, age = "Kim", 22 n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.") // The n and err return values from Fprintln are // those returned by the underlying io.Writer. if err != nil { fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err) } 或 for _, v := range d { fmt.Fprintln(f, v) if err != nil { fmt.Println(err) return } }
参考:
1. https://golang.google.cn/pkg/fmt/#Scanln