package main;
import (
"os"
"fmt"
"strconv"
)
func main() {
//打開文件,返回文件指針
file, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
fmt.Println(file);
file.Close();
//以讀寫方式打開文件,如果不存在,則創建
file2, error := os.OpenFile("./2.txt", os.O_RDWR|os.O_CREATE, 0766);
if error != nil {
fmt.Println(error);
}
fmt.Println(file2);
file2.Close();
//創建文件
//Create函數也是調用的OpenFile
file3, error := os.Create("./3.txt");
if error != nil {
fmt.Println(error);
}
fmt.Println(file3);
file3.Close();
//讀取文件內容
file4, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
//創建byte的slice用於接收文件讀取數據
buf := make([]byte, 1024);
//循環讀取
for {
//Read函數會改變文件當前偏移量
len, _ := file4.Read(buf);
//讀取字節數為0時跳出循環
if len == 0 {
break;
}
fmt.Println(string(buf));
}
file4.Close();
//讀取文件內容
file5, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
buf2 := make([]byte, 1024);
ix := 0;
for {
//ReadAt從指定的偏移量開始讀取,不會改變文件偏移量
len, _ := file5.ReadAt(buf2, int64(ix));
ix = ix + len;
if len == 0 {
break;
}
fmt.Println(string(buf2));
}
file5.Close();
//寫入文件
file6, error := os.Create("./4.txt");
if error != nil {
fmt.Println(error);
}
data := "我是數據\r\n";
for i := 0; i < 10; i++ {
//寫入byte的slice數據
file6.Write([]byte(data));
//寫入字符串
file6.WriteString(data);
}
file6.Close();
//寫入文件
file7, error := os.Create("./5.txt");
if error != nil {
fmt.Println(error);
}
for i := 0; i < 10; i++ {
//按指定偏移量寫入數據
ix := i * 64;
file7.WriteAt([]byte("我是數據"+strconv.Itoa(i)+"\r\n"), int64(ix));
}
file7.Close();
//刪除文件
del := os.Remove("./1.txt");
if del != nil {
fmt.Println(del);
}
//刪除指定path下的所有文件
delDir := os.RemoveAll("./dir");
if delDir != nil {
fmt.Println(delDir);
}
}