golang 文件操作


golang中對文件的操作方法封裝在os包中的type File struct中

File represents an open file descriptor.

創建新文件

Create

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

Create creates the named file, truncating it if it already exists.
If successful, methods on the returned File can be used for I/O;
If there is an error, it will be of type *PathError.

  1. 不會自動創建父目錄,如果要創建的文件父目錄不存在會出錯
  2. 文件已存在的情況下會覆蓋,相當於刪掉原來的,再建一個新的
	file,err := os.Create("C:/Users/markz/GO_PROJECT/src/xfile/mm.txt")
	defer file.Close()
	if err != nil {
		fmt.Println(err)
	}
	// file.WriteString("descriptor")

NewFile

func NewFile(fd uintptr, name string) *File 根據文件描述符和名字創建一個新的文件

創建標准輸入、輸出、錯誤

	 Stdout := os.NewFile(uintptr(syscall.Stdout), "/dev/stdout")
	 Stdout.WriteString("hello console can you hear me?")
	 defer Stdout.Close()
	 // Stdin  := os.NewFile(uintptr(syscall.Stdin), "/dev/stdin")
     // Stderr := os.NewFile(uintptr(syscall.Stderr), "/dev/stderr")

OpenFile

func OpenFile(name string, flag int, perm FileMode) (file *File, err error)

OpenFile is the generalized open call; most users will use Open or Create instead.
It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable.

以多種模式打開文件,其中O_CREATE模式能夠創建文件
flag 可以組合使用 O_RDONLY|O_WRONLY
fileMode r=4 w=2 x=1 0666 讀寫 0777 讀寫執行

func main(){
	// flag = os.O_CREATE 文件不存在就創建 存在會覆蓋  0666 新建的文件具有讀寫權限
	// file,err := os.OpenFile("sm.txt", os.O_CREATE,0666)

	// flag os.O_RDWR  讀寫方式打開 文件內容被覆蓋  不創建文件  filemode可以為0
	// file,err := os.OpenFile("sm.txt", os.O_RDWR,0)

	//  O_APPEND 最加模式打開文件
	file,err := os.OpenFile("sm.txt", os.O_APPEND,0)

	defer file.Close()
	if err != nil {
		fmt.Println(err)
	}

	file.WriteString(time.Now().Format("2006 01 02 15:04:05"))


}

O_RDONLY:只讀模式(read-only)
O_WRONLY:只寫模式(write-only)
O_RDWR:讀寫模式(read-write)
O_APPEND:追加模式(append)
O_CREATE:文件不存在就創建(create a new file if none exists.)
O_EXCL:與 O_CREATE 一起用,構成一個新建文件的功能,它要求文件必須不存在(used with O_CREATE, file must not exist)
O_SYNC:同步方式打開,即不使用緩存,直接寫入硬盤
O_TRUNC:打開並清空文件
至於操作權限perm,除非創建文件時才需要指定,不需要創建新文件時可以將其設定為0.雖然go語言給perm權限設定了很多的常量,但是習慣上也可以直接使用數字,如0666(具體含義和Unix系統的一致).
0666 讀寫權限

打開文件

Open

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

Open opens the named file for reading. If successful, methods on the returned file can be used for reading;
the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

只讀模式打開文件,相當於OpenFile(name string, os.O_RDONLY,0)

讀文件

Read

ioutil.ReadFile

不用打開和關閉文件,直接一次讀取整個文件內容,返回一個[]byte
文件較大時不推薦使用
逆操作 ioutil.WriteFile

io包還有一個文件拷貝方法io.Copy()

使用bufio

NewReader
func NewReader(rd io.Reader) *Reader 將File包裝成*Reader

NewReader returns a new Reader whose buffer has the default size.

ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
ReadLine() (line []byte, isPrefix bool, err error)
ReadLine tries to return a single line, not including the end-of-line bytes

寫文件

Write

func (f *File) Write(b []byte) (n int, err error)

Write writes len(b) bytes to the File. It returns the number of bytes written and an error, if any.
Write returns a non-nil error when n != len(b).

WriteString

func (f *File) WriteString(s string) (ret int, err error) 以字符串形式寫入

WriteString is like Write, but writes the contents of string s rather than an array of bytes.

使用bufio

wirter := bufio.NewWriter(file)

writer.WriteString(str) // 內容寫到緩存
 
writer.Flush()  // 將緩存數據寫入文件

文件夾的操作

os包中
創建和刪除Mkdir MkdirAll Remove RemoveAll
文件rename
Rename(oldname,newname string)error

其他

文件路徑的操作

在filepath包,主要有join split ext isabs dir abs

判斷文件是否存在

os.Stat() 根據返回錯誤判斷
err ==nil 文件或文件夾存在
os.IsNotExist(err) -> true 文件或文件夾不存在
else 不確定是否存在

func PathExists(fpath string) (bool,error){
	_,err := os.Stat(fpath)

	if err == nil{
		// 沒有錯誤 說明文件或文件夾已經存在
		return true, nil
	}

	if os.IsNotExist(err){
		// 不存在
		return false,nil
	}
	return false,errors.New("未知錯誤")
}

判斷是文件還是文件夾

os.Stat(file) 根據返回的fileinfo來判斷
fileino.IsDir() -> true 是文件夾 else 是文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM