Golang four ways to manipulate files

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang append content to end of file

words 349 Read the comments 0 likes 2

Golang read and write files, many tutorials on the web
But today there is a need to append the content to the end of the file
Google for a long time, did not find
Studied the file library for a while, finally let me find (blindfolded) the additional method
The main 2 functions are:

func (f *File) Seek(offset int64, whence int) (ret int64, err error)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)

    • Seek () to find the offset at the end of the file
    • Writeat () starts writing from the offset

Here are the chestnuts:
// fileName:文件名字(带全路径)// content: 写入的内容func appendToFile(fileName string, content string) error { // 以只写的模式,打开文件 f, err := os.OpenFile(fileName, os.O_WRONLY, 0644) if err != nil { fmt.Println("cacheFileList.yml file create failed. err: " + err.Error()) } else { // 查找文件末尾的偏移量 n, _ := f.Seek(0, os.SEEK_END) // 从末尾的偏移量开始写入内容 _, err = f.WriteAt([]byte(content), n) } defer f.Close() return err}

Take it, don't hesitate:)
Feel that the current domestic Golang document blog is still a little lack of points,
I hope we usually have any experience in coding to share with each other,
Make Golang more and more useful!

2016/08/31 Record:
I am a fool, obviously the simplest way can be achieved:
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_APPEND, 0666)
Open the file in the form of write and append ...

There are four ways to manipulate files below

Package Main

Import (
"Bufio"//Cache IO
"FMT"
"Io/ioutil"//io Toolkit
"IO"
"OS"
)

Func Check (e error) {
If E! = Nil {
Panic (e)
}
}

/**
* Determine if a file exists return true does not exist return false
*/
Func checkfileisexist (filename string) (bool) {
var exist = true;
If _, Err: = OS. Stat (filename); Os. Isnotexist (Err) {
exist = false;
}
return exist;
}

/**
from:http://www.isharey.com/?p=143
*/

Func Main () {
var wiretestring = "Test n"
var filename = "./output1.txt";
var f *os. File
var err1 error;
/***************************** first way: Using IO. WriteString writing to File ***********************************************/
If checkfileisexist (filename) {//If the file exists
F, err1 = OS. OpenFile (filename, os. O_append, 0666)//Open File
Fmt. Println ("file exists");
}else {
F, err1 = OS. Create (filename)//File creation
Fmt. PRINTLN ("File does not exist");
}
Check (ERR1)
N, err1: = Io. WriteString (f, wiretestring)//write to file (string)
Check (ERR1)
Fmt. Printf ("write%d bytes n", n);

/***************************** second way: Use Ioutil. WriteFile writing to File ***********************************************/
var D1 = []byte (wiretestring);
ERR2: = Ioutil. WriteFile ("./output2.txt", D1, 0666)//write file (byte array)
Check (ERR2)

/***************************** Third Way: Write files using file (write,writestring) ********************************************* **/
F, ERR3: = OS. Create ("./output3.txt")//File creation
Check (ERR3)
Defer F.close ()
N2, Err3: = F.write (D1)//write to file (byte array)
Check (ERR3)
Fmt. Printf ("write%d bytes n", N2)
N3, Err3: = f.writestring ("WRITESN")//write to file (byte array)
Fmt. Printf ("write%d bytes n", N3)
F.sync ()


 /***************************** Fourth Way:   use Bufio. Newwriter Write file ***********************************************/
 w: = Bufio. Newwriter (f)  //creates a new Writer object
 n4, Err3: = w.writestring ("Bufferedn")
 fmt. Printf ("write%d bytes n", N4)
 w.flush ()
 f.close ()
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.