1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package main import ( "fmt" "os" ) func main(){ fileName := "./file/a.txt" create, err := os.Create(fileName) if err != nil { fmt.Println("创建失败: " + err.Error()) return } fmt.Printf("创建成功! %v\n",create)
fileName := "./public/test.txt" file1, err := os.Open(fileName) if err != nil { fmt.Printf("os.Open 打开文件失败,err:%s \n" , err.Error()) } else { fmt.Printf("os.Open 打开文件成功,open:%v \n" , file1) defer file1.Close() } file2, err1 := os.OpenFile(fileName,os.O_CREATE,os.ModePerm) if err1 != nil { fmt.Printf("os.OpenFile 打开文件失败,err:%s \n" , err1.Error()) } else { fmt.Printf("os.OpenFile 打开文件成功,open:%v \n" , file2) defer file2.Close() }
b := make([]byte,1024) for { read, _ := file1.Read(b) if read == 0 { break } } fmt.Printf("读取内容: %s \n",b) _ = file1.Close()
fileName := "./public/hello.txt" file1, err := os.OpenFile(fileName,os.O_RDWR | os.O_CREATE | os.O_APPEND ,os.ModePerm ) if err != nil { fmt.Printf("os.OpenFile 打开文件失败,err:%s \n" , err.Error()) return } write, err := file1.Write([]byte("Go! Go! Let's Go!! 汉字 \n")) if err != nil { fmt.Printf("写入失败: %s \n",err.Error()) } fmt.Printf("写入字节数: %d \n",write) _ = file1.Close() }
|