From c4de5dbd88a273a711a2f9fe172910184616142e Mon Sep 17 00:00:00 2001 From: "rick.chan" Date: Tue, 13 Oct 2020 14:08:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20Go=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=93=8D=E4=BD=9C.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: rick.chan --- .../Language/Go/Basic/Go_文件操作.md | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Software/Development/Language/Go/Basic/Go_文件操作.md diff --git a/Software/Development/Language/Go/Basic/Go_文件操作.md b/Software/Development/Language/Go/Basic/Go_文件操作.md new file mode 100644 index 0000000..aff2472 --- /dev/null +++ b/Software/Development/Language/Go/Basic/Go_文件操作.md @@ -0,0 +1,54 @@ +# Go 文件操作 + +## 1.文本文件 + +### 1.1.创建 + +```go +f,err := os.Create(fileName) +defer f.Close() +if err !=nil { + fmt.Println(err.Error()) +} else { + _,err=f.Write([]byte("要写入的文本内容")) + checkErr(err) +} +``` + +### 1.2.读取 + +```go +f, err := os.OpenFile(fileName, os.O_RDONLY,0600) +defer f.Close() +if err !=nil { + fmt.Println(err.Error()) +} else { + contentByte,err=ioutil.ReadAll(f) + checkErr(err) + fmt.Println(string(contentByte)) +} +``` + +打开模式如下: + +```go +//打开方式 +const ( +//只读模式 +O_RDONLY int = syscall.O_RDONLY // open the file read-only. +//只写模式 +O_WRONLY int = syscall.O_WRONLY // open the file write-only. +//可读可写 +O_RDWR int = syscall.O_RDWR // open the file read-write. +//追加内容 +O_APPEND int = syscall.O_APPEND // append data to the file when writing. +//创建文件,如果文件不存在 +O_CREATE int = syscall.O_CREAT // create a new file if none exists. +//与创建文件一同使用,文件必须存在 +O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist +//打开一个同步的文件流 +O_SYNC int = syscall.O_SYNC // open for synchronous I/O. +//如果可能,打开时缩短文件 +O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened. +) +```