打开文件
func Open(name string) (file File, err error)
Open打开一个文件用于读取。如果操作成功,返回的文件对象的方法可用于读取数据;对应的文件描述符具有O_RDONLY模式。如果出错,错误底层类型是PathError。
概念说明: file
基础功能代码
package mainimport ("fmt""os")func main() {file, err := os.Open("d:/test.txt")if err != nil {fmt.Println("err = ", err)}fmt.Printf("file: %v \n", file) // &{0xc00008e780} 文件指针/文件对象/文件句柄err = file.Close()if err != nil {fmt.Println("关闭文件错误")}/*错误文件演示err = open d:/test01.txt: The system cannot find the file specified.file: <nil>关闭文件错误*/}
案例演示一(带缓冲-大文件)
读取文件内容,并显示在终端(带缓存区的方式),使用 os.Open(), file.Close(), bufio.NewReader(), reader.ReadString() 函数和方法
func NewReader(rd io.Reader) Reader
NewReader创建一个具有默认大小缓冲、从r读取的Reader。
func (b Reader) *ReadString(delim byte) (line string, err error)
ReadString读取直到第一次遇到delim字节,返回一个包含已读取的数据和delim字节的字符串。如果ReadString方法在读取到delim之前遇到了错误,它会返回在错误之前读取的数据以及该错误(一般是io.EOF)。当且仅当ReadString方法返回的切片不以delim结尾时,会返回一个非nil的错误。
package mainimport ("bufio""fmt""io""os")func main() {file, err := os.Open("d:/test.txt")if err != nil {fmt.Println("err = ", err)} else {// 创建带缓冲的 *reader/* const (// 默认缓冲区 4096 并不是一次读取完成,读一部分处理一部分,这样可以处理一些比较大的文件defaultBufSize = 4096) */reader := bufio.NewReader(file)// 循环读取内容for {// 读到一个换行就结束str, err := reader.ReadString('\n')if err == io.EOF {break}// 输出内容fmt.Print(str)}fmt.Println("文件读取结束")}fmt.Printf("file: %v \n", file) // &{0xc00008e780} 文件指针/文件对象/文件句柄/*错误文件演示err = open d:/test01.txt: The system cannot find the file specified.file: <nil>关闭文件错误*/// 案例// 当函数退出时,要及时关闭file,否则会有内存泄露defer func() {err = file.Close()if err != nil {fmt.Println("关闭文件错误")}}()}
案例演示二(一次性读取-小文件)
func ReadFile(filename string) ([]byte, error)
ReadFile 从filename指定的文件中读取数据并返回文件的内容。成功的调用返回的err为nil而非EOF。
因为本函数定义为读取整个文件,它不会将读取返回的EOF视为应报告的错误。
package mainimport "io/ioutil"func main() {// 一次性读取(小文件)file02, err := ioutil.ReadFile("d:/test.txt")if err != nil {fmt.Println("读取失败")}// 不需要显示的Open和Close, 都被封装到 ReadFile 函数里了fmt.Println("file02 = ", file02) // []byte// %s 直接输出字符串或者[]bytefmt.Printf("file02 = %s", file02)}
