golang 创建,读取,写入文件

栏目: 服务器 · 发布时间: 5年前

golang创建文本文件

f , err := os. Create ( fileName )

defer f. Close ()

if err != nil {

fmt. Println (err. Error ())

} else {

_ , err =f. Write ([] byte ("要写入的文本内容"))

checkErr (err)

}

golang读取文本文件

f , err := os. OpenFile ( fileName , os.O_RDONLY, 0600 )

defer f. Close ()

if err != nil {

fmt. Println (err. Error ())

} else {

contentByte , err =ioutil. ReadAll (f)

checkErr (err)

fmt. Println (string(contentByte) )

}

OpenFile用法:os.OpenFile(文件名,打开方式,打开模式)

//打开方式

const (

//只读模式

O_RDONLY int = syscall.O_RDONLY // open the file read-only.

//只写模式

O_WRONLY int = syscall.O_WRONLY // open the file write-only.

//可读可写

O_RDWR int = syscall.O_RDWR // open the file read-write.

//追加内容

O_APPEND int = syscall.O_APPEND // append data to the file when writing.

//创建文件,如果文件不存在

O_CREATE int = syscall.O_CREAT // create a new file if none exists.

//与创建文件一同使用,文件必须存在

O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist

//打开一个同步的文件流

O_SYNC int = syscall.O_SYNC // open for synchronous I/O.

//如果可能,打开时缩短文件

O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.

)

//打开模式

const (

ModeDir FileMode = 1 << ( 32 - 1 - iota ) // d: is a directory 文件夹模式

ModeAppend // a: append-only 追加模式

ModeExclusive // l: exclusive use 单独使用

ModeTemporary // T: temporary file (not backed up) 临时文件

ModeSymlink // L: symbolic link 象征性的关联

ModeDevice // D: device file 设备文件

ModeNamedPipe // p: named pipe (FIFO) 命名管道

ModeSocket // S: Unix domain socket Unix 主机 socket

ModeSetuid // u: setuid 设置uid

ModeSetgid // g: setgid 设置gid

ModeCharDevice // c: Unix character device, when ModeDevice is set Unix 字符设备,当设备模式是设置Unix

ModeSticky // t: sticky 粘性的

// Mask for the type bits. For regular files, none will be set. bit位遮盖.不变的文件设置为none

ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

ModePerm FileMode = 0777 // Unix permission bits 权限位.

)

golang写入文本文件

f , err := os. OpenFile ( fileName , os.O_WRONLY|os.O_TRUNC, 0600 )

defer f. Close ()

if err != nil {

fmt. Println (err. Error ())

} else {

_ , err =f. Write ([] byte ("要写入的文本内容"))

checkErr (err)

}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

免费

免费

克里斯•安德森 / 蒋旭峰、冯斌、璩静 / 中信出版社 / 2012-10 / 68.00元

一种商业模式既可以统摄未来的市场,也可以挤垮当前的市场——在我们这个现代经济社会里,这并不是一件不可能的事情。 “免费”就是这样的一种商业模式,它所代表的正是数字化网络时代的商业未来。 在《免费》这本书中,克里斯•安德森认为,新型的“免费”并不是一种左口袋出、右口袋进的营销伎俩,而是一种把货物和服务的成本压低到零的新型卓越能力。在20世纪“免费”是一种强有力的推销手段,而在21世纪它已经成为......一起来看看 《免费》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具