Go语言文件操作

Python013

Go语言文件操作,第1张

本文主要介绍了Go语言中文件读写的相关操作。

文件是什么?

计算机中的文件是存储在外部介质(通常是磁盘)上的数据集合,文件分为文本文件和二进制文件。

os.Open() 函数能够打开一个文件,返回一个 *File 和一个 err 。对得到的文件实例调用 close() 方法能够关闭文件。

为了防止文件忘记关闭,我们通常使用defer注册文件关闭语句。

Read方法定义如下:

它接收一个字节切片,返回读取的字节数和可能的具体错误,读到文件末尾时会返回 0 和 io.EOF 。 举个例子:

使用for循环读取文件中的所有数据。

bufio是在file的基础上封装了一层API,支持更多的功能。

io/ioutil 包的 ReadFile 方法能够读取完整的文件,只需要将文件名作为参数传入。

os.OpenFile() 函数能够以指定模式打开文件,从而实现文件写入相关功能。

其中:

name :要打开的文件名 flag :打开文件的模式。 模式有以下几种:

perm :文件权限,一个八进制数。r(读)04,w(写)02,x(执行)01。

命令如下:

直接在终端中输入gohelp即可显示所有的go命令以及相应命令功能简介,主要有下面这些:

build:编译包和依赖;clean:移除对象文件;doc:显示包或者符号的文档;env:打印go的环境信息;bug:启动错误报告;fix:运行gotoolfix;fmt:运行gofmt进行格式化;generate:从processingsource生成go文件

get:下载并安装包和依赖;install:编译并安装包和依赖;list:列出包;run:编译并运行go程序;test:运行测试;tool:运行go提供的工具;version:显示go的版本;vet:运行gotoolvet;命令的使用方式为:gocommand[args],除此之外,可以使用gohelp;来显示指定命令的更多帮助信息。;在运行gohelp时,不仅仅打印了这些命令的基本信息,还给出了一些概念的帮助信息:;c:Go和c的相互调用;buildmode:构建模式的描述;filetype:文件类型;gopath:GOPATH环境变量

environment:环境变量;importpath:导入路径语法;packages:包列表的描述;testflag:测试符号描述;testfunc:测试函数描述等。

1、解压压缩包到go工作目录,如解压到E:\opensource\go\go,解压后的目录结构如下:

E:\opensource\go\go

├─api

├─bin

│ ├─go.exe

│ ├─godoc.exe

│ └─gofmt.exe

├─doc

├─include

├─lib

├─misc

├─pkg

├─src

└─test

2、增加环境变量GOROOT,取值为上面的go工作目录

3、Path环境变量中添加"%GOROOT%\bin",以便能够直接调用go命令来编译go代码,至此go编译环境就配置好了

注:如果不想手动设置系统环境变量,也可下载go启动环境批处理附件,

修改goenv.bat文件中的GOROOT值为上面的go工作目录后直接双击该bat文件,go编译环境变量即设置完成。

4、测试go编译环境,启动一个cmd窗口,直接输入go,看到下面的提示就是搭建成功了

E:\opensource\go\go>go

Go is a tool for managing Go source code.

Usage:

go command [arguments]

The commands are:

build compile packages and dependencies

clean remove object files

doc run godoc on package sources

env print Go environment information

fix run go tool fix on packages

fmt run gofmt on package sources

get download and install packages and dependencies

install compile and install packages and dependencies

listlist packages

run compile and run Go program

testtest packages

toolrun specified go tool

version print Go version

vet run go tool vet on packages

Use "go help [command]" for more information about a command.

Additional help topics:

gopath GOPATH environment variable

packagesdescription of package lists

remote remote import path syntax

testflagdescription of testing flags

testfuncdescription of testing functions

Use "go help [topic]" for more information about that topic.

5、编译helloworld测试程序,go语言包中test目录带有helloworld.go测试程序,源码见"附一 helloworld.go",

直接调用"go build helloworld.go"就生成了"helloworld.exe"可执行程序,运行一下这个程序看到了我们期望的hello,wolrd。

E:\opensource\go\go\test>go build helloworld.go

E:\opensource\go\go\test>helloworld.exe

hello, world

E:\opensource\go\go\test>

附一 helloworld.go

// cmpout

// Copyright 2009 The Go Authors. All rights reserved.

// Use of this source code is governed by a BSD-style

// license that can be found in the LICENSE file.

// Test that we can do page 1 of the C book.

package main

func main() {

print("hello, world\n")

}