Go 文件操作 文件打开和关闭 os.Open(name string)(*File,error) File.Close()

文件  基本介绍


 文件,对我们并不陌生,文件是数据源(保存数据的地方)的一种,比如大家经常使用的word文档,txt文件,excel文件……都是文件。文件最主要的作用就是保存数据它既可以保存一张图片,也可以保持视频,声音…

文件在程序当中是以流的形式来操作的。

流:数据在数据源(文件)和程序(内存)之间经历的路径

  • 输入流:数据从数据源(文件)到程序(内存)的路径                读文件操作
  • 输出流:数据从程序(内存))到数据源(文件)的路径             写文件操作

在go中对文件的操作是由哪个结构体来提供的呢?在go里面有个包叫os包,包里面有个结构体叫File,封装了对所有文件的操作

os package - os - pkg.go.devhttps://pkg.go.dev/os#File

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 FileInfo, 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 []FileInfo, err error)
func (f *File) Readdirnames(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, off int64) (n int, err error)
func (f *File) Write(b []byte) (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

可以看到上面大多是和File结构体绑定的方法(前面还是一些普通的方法)File代表一个打开文件的对象,有些时候我们称之为文件句柄。

文本文件可以使用string去处理,也可以使用byte去处理,如果处理二进制文件只能使用[]byte去处理。中间不能[]用byte转化为string去处理。

总结:后面我们操作文件会经常使用到os.File结构体。

 

打开关闭文件📃 os.Open  File.Close


对一个文件要进行操作,那么首先应该打开一个文件。 

  1. 打开一个文件进行读操作∶os.Open(name string)(*File,error)  (返回的是file结构体的指针,简而言之文件是一个指针类型
  2. 关闭一个文件∶File.Close()
func Open(name string) (file *File, err error)

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

func Open(name string) (*File, error) 这个Open是os包里面的一个函数,并不是和结构体绑定的方法(打开打开指定文件进行读取,如果成功,则可以使用返回文件上的方法进行读取)(返回的是File结构体的指针,如果打开失败返回error)

这里返回值是一个打开文件之后的File结构体指针,因为在打开的时候文件路径可能是不存在的,也有可能因为文件权限的问题,所以打开文件的时候还要返回一个失败。

当对文件操作完毕之后,比如读或者写,做完之后要注意一件事情,关闭文件。

func (*File) Close 

func (f *File) Close() error

Close 关闭文件,使其无法用于 I/O。关闭错误会返回error(要及时关闭文件句柄,否则会有内存泄漏)

示例

//获取到文件结构体指针就可以对文件进行读写操作
//file有些叫文件对象,有些叫file指针,有些叫文件句柄。

	path := "test.txt"
	file,err := os.Open(path)  
	if err != nil{
		fmt.Println("open file err:",err)
	}
	fmt.Printf("file = %v",file)

	err = file.Close()
	if err !=nil{
		fmt.Println("close file error")
	}

可以看到就是一个地址,指针就是一个地址,文件就是一个指针类型,文件句柄其实也是一个指针。

file = &{0xc000056180}

 如果文件不存在

open file err: open test.txt1: no such file or directory
file = <nil>
close file error

可以看到关闭的时候也报错了,因为文件都没打开,怎么去关闭。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无组件ASP文件上传源代码 记得在建立一个文件夹"updata" saveannounce_upload.asp 上传页 ------------------------------------ body {font-size:9pt;} input {font-size:9pt;} 文件上传 文件 ------------------------------------ saveannouce_upfile.asp 保存文件到服务器 ------------------------------------ 文件上传 <% dim upload,file,formName,formPath set upload=new upload_5xSoft ''建立上传对象 formPath=upload.form("filepath") ''在目录后加(/) if right(formPath,1)"/" then formPath=formPath&"/" for each formName in upload.file ''列出所有上传了的文件 set file=upload.file(formName) ''生成一个文件对象 if file.filesize<100 then response.write "请先选择你要上传的文件 [ 重新上传 ]" response.end end if if file.filesize>500*1000 then '设置上传文件大小为500K response.write "文件大小超过了限制 500K [ 重新上传 ]" response.end end if if file.FileSize>0 then ''如果 FileSize > 0 说明有文件数据 file.SaveAs Server.mappath("updata\"&file.FileName) ''保存文件 end if set file=nothing next set upload=nothing response.write "文件上传成功 [ 继续上传 ]" %> ------------------------------------ upload.inc 建立upload对象 ------------------------------------ dim upfile_5xSoft_Stream Class upload_5xSoft dim Form,File,Version Private Sub Class_Initialize dim iStart,iFileNameStart,iFileNameEnd,iEnd,vbEnter,iFormStart,iFormEnd,theFile dim strDiv,mFormName,mFormValue,mFileName,mFileSize,mFilePath,iDivLen,mStr Version="" if Request.TotalBytes<1 then Exit Sub set Form=CreateObject("Scripting.Dictionary") set File=CreateObject("Scripting.Dictionary") set upfile_5xSoft_Stream=CreateObject("Adodb.Stream") upfile_5xSoft_Stream.mode=3 upfile_5xSoft_Stream.type=1 upfile_5xSoft_Stream.open upfile_5xSoft_Stream.write Request.BinaryRead(Request.TotalBytes) vbEnter=Chr(13)&Chr(10) iDivLen=inString(1,vbEnter)+1 strDiv=subString(1,iDivLen) iFormStart=iDivLen iFormEnd=inString(iformStart,strDiv)-1 while iFormStart 0 and iFileNameStartiStart then mFileSize=iEnd-iStart-4 else mFileSize=0 end if set theFile=new FileInfo theFile.FileName=getFileName(mFileName) theFile.FilePath=getFilePath(mFileName) theFile.FileSize=mFileSize theFile.FileStart=iStart+4 theFile.FormName=FormName file.add mFormName,theFile else iStart=inString(iEnd+1,vbEnter&vbEnter) iEnd=inString(iStart+4,vbEnter&strDiv) if iEnd>iStart then mFormValue=subString(iStart+4,iEnd-iStart-4) else mFormValue="" end if form.Add mFormName,mFormValue end if iFormStart=iformEnd+iDivLen iFormEnd=inString(iformStart,strDiv)-1 wend End Sub Private Function subString(theStart,theLen) dim i,c,stemp upfile_5xSoft_Stream.Position=theStart-1 stemp="" for i=1 to theLen if upfile_5xSoft_Stream.EOS then Exit for c=ascB(upfile_5xSoft_Stream.Read(1)) If c > 127 Then if upfile_5xSoft_Stream.EOS then Exit for stemp=stemp&Chr(AscW(ChrB(AscB(upfile_5xSoft_Stream.Read(1)))&ChrB(c))) i=i+1 else stemp=stemp&Chr(c) End If Next subString=stemp End function Private Function inString(theStart,varStr) dim i,j,bt,theLen,str InString=0 Str=toByte(varStr) theLen=LenB(Str) for i=theStart to upfile_5xSoft_Stream.Size-theLen if i>upfile_5xSoft_Stream.size then exit Function upfile_5xSoft_Stream.Position=i-1 if AscB(upfile_5xSoft_Stream.Read(1))=AscB(midB(Str,1)) then InString=i for j=2 to theLen if upfile_5xSoft_Stream.EOS then inString=0 Exit for end if if AscB(upfile_5xSoft_Stream.Read(1))AscB(MidB(Str,j,1)) then InString=0 Exit For end if next if InString0 then Exit Function end if next End Function Private Sub Class_Terminate form.RemoveAll file.RemoveAll set form=nothing set file=nothing upfile_5xSoft_Stream.close set upfile_5xSoft_Stream=nothing End Sub Private function GetFilePath(FullPath) If FullPath "" Then GetFilePath = left(FullPath,InStrRev(FullPath, "\")) Else GetFilePath = "" End If End function Private function GetFileName(FullPath) If FullPath "" Then GetFileName = mid(FullPath,InStrRev(FullPath, "\")+1) Else GetFileName = "" End If End function Private function toByte(Str) dim i,iCode,c,iLow,iHigh toByte="" For i=1 To Len(Str) c=mid(Str,i,1) iCode =Asc(c) If iCode255 Then iLow = Left(Hex(Asc(c)),2) iHigh =Right(Hex(Asc(c)),2) toByte = toByte & chrB("&H"&iLow) & chrB("&H"&iHigh) Else toByte = toByte & chrB(AscB(c)) End If Next End function End Class Class FileInfo dim FormName,FileName,FilePath,FileSize,FileStart Private Sub Class_Initialize FileName = "" FilePath = "" FileSize = 0 FileStart= 0 FormName = "" End Sub Public function SaveAs(FullPath) dim dr,ErrorChar,i SaveAs=1 if trim(fullpath)="" or FileSize=0 or FileStart=0 or FileName="" then exit function if FileStart=0 or right(fullpath,1)="/" then exit function set dr=CreateObject("Adodb.Stream") dr.Mode=3 dr.Type=1 dr.Open upfile_5xSoft_Stream.position=FileStart-1 upfile_5xSoft_Stream.copyto dr,FileSize dr.SaveToFile FullPath,2 dr.Close set dr=nothing SaveAs=0 end function End Class

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值