英文:
PHP file_get_contents in Go lang
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是一个新手,对Golang不太熟悉。实际上,我是一个PHP开发者。
我需要在Golang中使用file_get_contents
函数。
你能提供这个函数的代码或者建议一个适合我需求的Golang库吗?
注意:请记住,file-get-contents
不仅仅是"读取文件"。
英文:
I'm new to Golang. Actually I'm a PHP developer.
I need file_get_contents
function in Golang.
Can you please provide code for this or suggest Golang library for my requirement.
Note: Keep in mind file-get-contents
does more than just "read a file".
答案1
得分: 7
我不认为有一个与file-get-contents.php
一样多功能的独特的golang函数。
-
用于读取整个文件的函数:"How Can i read a whole file into a string variable in golang?"(是的,
io/ioutil/#ReadFile
) -
用于读取http页面的函数:
http.Get
(参见此示例)res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } robots, err := ioutil.ReadAll(res.Body) res.Body.Close()
-
用于读取文件部分内容的函数:参见"Go by Example: Reading Files"
> 你经常希望对文件的读取方式和读取部分进行更多的控制。
对于这些任务,首先打开文件以获取os.File值。
f, err := os.Open("/tmp/dat")
check(err)
# 你也可以定位到文件中的已知位置并从那里读取。
o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))
英文:
I don't think there is one unique golang function as versatile as file-get-contents.php
.
-
For reading a all file: "How Can i read a whole file into a string variable in golang?" (yes,
io/ioutil/#ReadFile
) -
For reading an http page:
http.Get
(see this example)res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } robots, err := ioutil.ReadAll(res.Body) res.Body.Close()
-
For reading part of a file: see "Go by Example: Reading Files"
> You’ll often want more control over how and what parts of a file are read.
For these tasks, start by Opening a file to obtain an os.File value.
f, err := os.Open("/tmp/dat")
check(err)
# You can also Seek to a known location in the file and Read from there.
o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论