文件操作
文件的基本操作
读文件
代码语言:javascript
复制func readFile(){
filename := "./aaa.log"
file, err := os.Open(filename)
if err != nil {
fmt.Printf("open %s is error,error %vn",filename,err)
return
}
//关闭文件句柄
defer func() {
file.Close()
}()
//读取文件
var buf[4096]byte
var content []byte
for {
n,err := file.Read(buf[:])
if err != nil && err != io.EOF {
fmt.Printf("Read %s failed,error %vn",filename,err)
return
}
//读取到文件末尾
if err == io.EOF {
break
}
validBuf := buf[0:n]
//fmt.Printf("%sn",string(validBuf))
content = append(content,validBuf...)
}
fmt.Printf("content :%sn",content)
}
func main() {
readFile()
}
代码语言:javascript
复制func buffioRead() {
//使用缓存的方式读取文件
filename := "./aaa.log"
file,err := os.Open(filename)
if err != nil {
fmt.Printf("read file %s faild,error :%vn",filename,err)
return
}
defer file.Close()
reader := bufio.NewReader(file)
var content []byte
var buf [4096]byte
for {
n,err := reader.Read(buf[:])
if err != nil && err != io.EOF {
fmt.Printf("read %s failed,error is :%vn",filename,err)
return
}
//读取到文件末尾
if err == io.EOF {
break
}
validBuf := buf[0:n]
content = append(content,validBuf...)
}
fmt.Printf("content :%sn",content)
}
func main() {
buffioRead()
}
- ioutil文件读取整个文件: 读取小文件使用,比如配置文件需求
代码语言:javascript
复制func ioutilRead(){
filename := "./aaa.log"
content,err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf("read file %s error :%vn",filename,err)
return
}
fmt.Printf("content %sn",string(content))
}
代码语言:javascript
复制文件压缩: gzip -c 源文件 > 压缩文件.gz
目录压缩: gzip -r 目录
解压: gzip -d 压缩文件.gz
代码语言:javascript
复制func gzfileRead() {
filename := "./aaa.gz"
file,err := os.Open(filename)
if err !=nil {
fmt.Printf("can not open %s,err: %vn",filename,err)
return
}
defer file.Close()
reader,err := gzip.NewReader(file)
if err != nil {
fmt.Printf("gzfile read faild,err: %vn",err)
return
}
// reader := bufio.NewReader(file) 读取出来的内容是二进制的
var content []byte
var buf [4096]byte
for {
n,err := reader.Read(buf[:])
if err != nil && err != io.EOF {
fmt.Printf("read %s faild,err: %vn",filename,err)
return
}
if n > 0 {
validBuf := buf[0:n]
content = append(content,validBuf...)
}
if err == io.EOF {
break
}
}
fmt.Printf("content,:%sn",string(content))
}
写文件
代码语言:javascript
复制func checkFileExists(filename string) bool {
// 文件存在检测
_,err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return true
}
func createWriteFiles() {
filename := "./bbb.txt"
var file *os.File
var err error
// 文件追加或创建
if checkFileExists(filename) {
file,err = os.OpenFile(filename,os.O_APPEND|os.O_WRONLY,0755)
}else {
file,err = os.Create(filename)
}
if err != nil {
fmt.Printf("create file %s,error :%v n", filename, err)
return
}
defer file.Close()
//写入文件
n,err := file.WriteString("hello world")
if err != nil {
fmt.Printf("write faild,err: %vn",err)
return
}
fmt.Printf("write %d succn",n)
}
代码语言:javascript
复制func ioutilWrite() {
filename := "./bbb.txt"
str := "ssssaddvfv"
ioutil.WriteFile(filename,[]byte(str),0755)
}
代码语言:javascript
复制func checkFileExists(filename string) bool {
// 文件存在检测
_,err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return true
}
func bufioWriteFile() {
filename := "./ccc.txt"
var file *os.File
var err error
if checkFileExists(filename) {
file,err = os.OpenFile(filename,os.O_WRONLY|os.O_APPEND,0666)
}else {
file,err = os.Create(filename)
}
if err != nil {
fmt.Printf("write file error:%vn",err)
return
}
defer file.Close()
//bufio文件写入
writer := bufio.NewWriter(file)
writer.WriteString("helloworld,wxxx")
writer.Flush() //将缓存数据刷到文件
}
代码语言:javascript
复制func copyFile(destFile,srcFile string) (written int64,err error) {
src,err := os.Open(srcFile)
if err != nil {
fmt.Printf("open src file error:%vn",err)
return
}
defer src.Close()
dst,err := os.OpenFile(destFile,os.O_WRONLY|os.O_APPEND,0666)
if err != nil {
return
}
return io.Copy(dst,src)
}
func main() {
copyFile("./ddd.txt","aaa.log")
}
代码语言:javascript
复制func terminalControl() {
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("hello")
writer.Flush()
//读取终端数据
reader := bufio.NewReader(os.Stdin)
data,err := reader.ReadString('n')
if err != nil {
fmt.Printf("read fro terminal error:%vn",err)
}
fmt.Fprintf(os.Stdout,"data:%sn",data)
}
代码语言:javascript
复制func addWord(charCount map[rune]int,char rune){
count,ok := charCount[char]
if !ok {
charCount[char] = 1
}else {
charCount[char] = count 1
}
}
func main() {
str := ""
fmt.Scanln(&str)
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("")
writer.Flush()
//读取终端数据
reader := bufio.NewReader(os.Stdin)
data,err := reader.ReadString('n')
if err != nil {
fmt.Printf("read fro terminal error:%vn",err)
}
fmt.Fprintf(os.Stdout,"data:%sn",data)
var charCount map[rune]int = make(map[rune]int,10)
var chars []rune = []rune(data)
for i:=0;i<len(chars);i {
addWord(charCount,chars[i])
}
for key,val := range charCount {
fmt.Printf("keys:%c val: %dn",key,val)
}
}
命令行参数
代码语言:javascript
复制func main() {
//获取参数个数
fmt.Printf("args count:%dn",len(os.Args))
//打印参数
for index,v := range os.Args {
fmt.Printf("args:%d,value:%sn",index,v)
}
}
flag包的使用
代码语言:javascript
复制func flagArgs() {
var num int
var mode string
flag.IntVar(&num,"num",16,"number of password")
flag.StringVar(&mode,"mode","mix","mode of password generate")
flag.Parse()
fmt.Printf("num:%d,mode:%sn",num,mode)
}