Go - File

Go - File 首页 / Golang入门教程 / Go - File

在运行中,os.file对象用于文件操作。 os.File对象也称为文件句柄。

os包中的open函数用于在Go中打开文件。 io/ioutil包中的ReadFile()用于读取文件。此方法返回[] byte个读取字节的数组。 file.WriteString方法可用于写入文件。

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-file-io.html

来源:LearnFk无涯教程网

我们在打开文件后立即使用defer file.close()来确保函数完成后立即关闭文件。如果文件不存在或程序没有足够的权限打开文件,则

inputFile,inputError = os.Open(" input.dat")导致错误。

Go文件I/O示例

package main
import (
   "os"
   "log"
   "io/ioutil"
   "fmt"
)
func main() {
   file, err := os.Create("file.txt")
   if err != nil {
      log.Fatal(err)
   }
   file.WriteString("Hi... there")
   file.Close()
   stream, err:= ioutil.ReadFile("file.txt")
   if err != nil {
      log.Fatal(err)
   }
   readString := string(stream)
   fmt.Println(readString)
}

输出:

Hi... there

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

人工智能基础课 -〔王天一〕

Go语言从入门到实战 -〔蔡超〕

网络编程实战 -〔盛延敏〕

说透敏捷 -〔宋宁〕

微信小程序全栈开发实战 -〔李艺〕

程序员的个人财富课 -〔王喆〕

深入剖析Java新特性 -〔范学雷〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)