文件

文件

【1】文件是什么?
文件是保存数据的地方,是数据源的一种,比如大家经常使用的word文档、txt文件、excel文件、jpg文件.都是文件。文件最主要的作用就是保存
数据,它既可以保存一张图片,也可以保持视频,声音..
【2】os包下的File结构体封装了对文件的操作:

api :https://studygolang.com/pkgdoc

  • type File
    func Create(name string) (file *File, err error)
    func Open(name string) (file *File, err error)
    • func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
    func NewFile(fd uintptr, name string) *File
    • func Pipe() (r *File, w *File, err error)
    ·func (f *File) Name() string
    ·func (f *File) Stat()(fi Filelnfo, err error)
    ·func (f *File) Fd() uintptr
    func (f *File) Chdir() error
    ·func (f *File) Chmod(mode FileMode) error
    func (f *File) Chown(uid, gid int) error
    ·func (f *File) Readdir(n int)(fi Fillelnfo, err eror)
    ·func (f *File) Readdimames(n int) (names [string, err error)
    •func (f *File) Truncate(size int64) error
    ·func (f *File) Read(b byte) (n int, err error)
    ·func (f *File)ReadAt(b byte, offint64) (nint, err error)
    · func (f *File) Write(b Jbyte) (n int, err error)
    ·func (f *File) WriteString(s string) (ret int, err error)
    func (f *File) WriteAt(b byte, off int64) (n int, err error)
    func (f *File) Seek(offset int64, whence int) (ret int64, err error)
    func (f *File) Sync() (err error)
    func (f *File) Close() error

【3】File结构体---打开文件和关闭文件:
(1)打开文件,用于读取:(函数)

func Open

func Open(name string) (file *File, err error)

Open打开一个文件用于读取。如果操作成功,返回的文件对象的方法可用于读取数据;对应的文件描述符具有O_RDONLY模式。如果出错,错误底层类型是*PathError。

传入一个字符串(文件的路径),返回的是文件的指针,和是否打开成功

(2)关闭文件:(方法)

func (*File) Close

func (f *File) Close() error

Close关闭文件f,使文件不能用于读写。它返回可能出现的错误。

使文件不能用于读写。它返回可能出现的错误

【4】案例:

package main
import (
	"fmt"
	"os"
)

func main()  {
	file, err := os.Open("D:/workstation/code/gocode/unit11/demo01/test.txt")
	if err != nil {
		fmt.Println("文件打开出错:",err)
	}

	fmt.Printf("文件=%v",file)

	err2 := file.Close()
	if err2 != nil {
		fmt.Println("文件关闭出错:",err2)
	}

}

posted @ 2025-07-02 18:13  hutaodd  阅读(46)  评论(0)    收藏  举报