go語言實現檔案的讀寫和拷貝

2021-10-10 11:25:04 字數 1880 閱讀 5886

package file_utils

import (

"bufio"

"fmt"

"io"

"io/ioutil"

"os"

)// 開啟檔案

func openfile(filepath string) else

fmt.println(file)

err=file.close()

if err==nil

}//普通方式讀取檔案

func readfilecontent(filepath string)

//必須關閉(否則可能有記憶體洩漏問題),defer修飾的**塊最後執行

defer

file.close();

//使用緩衝區讀取檔案,緩衝區大小設定為1024個位元組

buffer:=make(byte,1024,1024)

//通過bufio和file建立reader物件

reader:=bufio.newreader(file)

forfmt.println(string(buffer)) }}

//使用ioutil讀取檔案,可以不顯式建立file物件,也不需要顯示close檔案。

//不用建立緩衝區讀取檔案,但這種方式只適用於檔案比較小的情況

func readfilebyioutil(filepath string)

//位元組切片轉換為字串

fmt.println(string(content))

}//建立新檔案並寫入資料

func createfileandwrite(filepath string)

//最後關閉檔案

defer file.close()

str:="a fellow doesn't last long on what he has done. he's got to keep on delivering as he goes along."

writer:=bufio.newwriter(file)

writer.writestring(str)

//因為write帶快取,使用flush方法才能將資料寫入到檔案

writer.flush()

}// 使用copy函式完成檔案拷貝(也可以使用io包下的read()和write()方法實現)

func copyfile(srcfilepath string,destfilepath string,)(int64,error)

destfile, deste := os.openfile(destfilepath, os.o_wronly|os.o_create, 0777)

if(deste!=nil)

//關閉檔案

defer srcfile.close()

defer destfile.close()

//使用copy函式完成拷貝功能

return io.copy(destfile,srcfile)

}//使用ioutil完成檔案的複製功能

//使用ioutil不用顯式地關閉檔案

func copyfilebyutil(srcfilepath string,destfilepath string,)(int,error)

err := ioutil.writefile(destfilepath, input, 0666)

if(err!=nil)

return len(input),nil

}

主函式:      

C語言實現檔案讀寫

關於c語言的檔案讀寫,我將介紹下面這幾種方式 1.fputc 函式 fputc c,fp 用於將乙個字元寫入檔案 其中,fp為檔案指標變數 c為要寫入的字元,可以是字元常量或字元型變數。函式返回值 如果執行成功,返回寫入的字元 否則,返回eof。int main else fclose fp 關閉檔...

C語言實現簡單的檔案讀寫

這是乙個用c語言進行檔案讀取檔案的乙個控制台程式。讀取的檔案為乙個txt檔案,裡面存放乙個5 5的矩陣,對檔案的處理為矩陣乘2。首先要想更好的理解這個 必須了解計算機處理檔案的具體過程 檔案讀取的資料流。本文參考譚浩強老師的至尊寶典 c語言程式設計 1.定義檔案指標 file in,out 定義檔案...

go語言的讀寫檔案

以create方法寫檔案 以新建的方式開啟,create方法每次開啟都會清空裡面的內容 f,err os.create hah.txt if err nil defer f.close f.writestring hello,kingsoft 以open唯讀的方式開啟 open是以唯讀的方式開啟,只...