Golang How to read input filename in Go

huangapple go评论90阅读模式
英文:

Golang How to read input filename in Go

问题

我想在我的input.txt文件上运行我的go文件,当我输入go run命令时,我的go程序将读取input.txt文件,即:

go run goFile.go input.txt

我不想在我的goFile.go代码中放入input.txt,因为我的go文件应该能够运行任何输入名称,而不仅仅是input.txt

我尝试过ioutil.ReadAll(os.Stdin),但我需要更改我的命令为:

go run goFile.go < input.txt

我只使用fmtosbufioio/ioutil包。是否可能在不使用其他包的情况下实现这一点?

英文:

I would like to run my go file on my input.txt where my go program will read the input.txt file when I type in go run command ie:

go run goFile.go input.txt

I don't want to put input.txt in my goFile.go code since my go file should run on any input name not just input.txt.

I try ioutil.ReadAll(os.Stdin) but I need to change my command to

go run goFile.go &lt; input.txt

I only use package fmt, os, bufio and io/ioutil. Is it possible to do it without any other packages?

答案1

得分: 13

请查看您已经使用的io/ioutil包的文档。

它有一个专门用于此目的的函数:ReadFile()

func ReadFile(filename string) ([]byte, error)

示例用法:

func main() {
    // os.Args的第一个元素始终是程序名称,
    // 所以我们至少需要2个参数来作为文件名参数。
    if len(os.Args) < 2 {
        fmt.Println("缺少参数,请提供文件名!")
        return
    }
    data, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("无法读取文件:", os.Args[1])
        panic(err)
    }
    // data是文件内容,您可以使用它
    fmt.Println("文件内容为:")
    fmt.Println(string(data))
}
英文:

Please take a look at the package documentation of io/ioutil which you are already using.

It has a function exactly for this: ReadFile()

func ReadFile(filename string) ([]byte, error)

Example usage:

func main() {
    // First element in os.Args is always the program name,
    // So we need at least 2 arguments to have a file name argument.
    if len(os.Args) &lt; 2 {
        fmt.Println(&quot;Missing parameter, provide file name!&quot;)
        return
    }
    data, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println(&quot;Can&#39;t read file:&quot;, os.Args[1])
        panic(err)
    }
    // data is the file content, you can use it
    fmt.Println(&quot;File content is:&quot;)
    fmt.Println(string(data))
}

答案2

得分: 1

首先,你检查提供的参数。如果第一个参数满足输入文件的条件,那么你使用ioutil.ReadFile方法,参数为os.Args的结果。

package main

import (
	"fmt"
	"os"
	"io/ioutil"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage : " + os.Args[0] + " file name")
		os.Exit(1)
	}
	
	file, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println("无法读取文件")
		os.Exit(1)
	}
	// 对文件进行操作
	fmt.Print(string(file))
}

另一种可能性是使用:

f, err := os.Open(os.Args[0])

但是对于这种情况,你需要提供要读取的字节数:

b := make([]byte, 5) // 5 是长度
n, err := f.Read(b)
fmt.Printf("%d bytes: %s\n", n, string(b))
英文:

Firs you check for the provided argument. If the first argument satisfy the condition of an input file, then you use the ioutil.ReadFile method, providing parameter the os.Args result.

package main

import (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;io/ioutil&quot;
)

func main() {
	if len(os.Args) &lt; 1 {
		fmt.Println(&quot;Usage : &quot; + os.Args[0] + &quot; file name&quot;)
		os.Exit(1)
	}
	
	file, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(&quot;Cannot read the file&quot;)
		os.Exit(1)
	}
	// do something with the file
	fmt.Print(string(file))
}

Another possibility is to use:

f, err := os.Open(os.Args[0])

but for this you need to provide the bytes lenght to read:

b := make([]byte, 5) // 5 is the length
n, err := f.Read(b)
fmt.Printf(&quot;%d bytes: %s\n&quot;, n, string(b))

答案3

得分: 0

要在命令行中通过输入参数(例如abc.txt)运行.go文件,我们需要主要使用os、io/ioutil和fmt包。此外,为了读取命令行参数,我们使用os.Args。以下是示例代码:

package main

import (
	"fmt"
	"os"
	"io/ioutil"
)

func main() {
	fmt.Println("Hi guys  ('-')")
	input_files := os.Args[1:]
	if len(input_files) < 1 {
		fmt.Println("Not detected files.")
	} else {
		fmt.Println("File_name is:", input_files[0])
		content, err := ioutil.ReadFile(input_files[0])
		if err != nil {
			fmt.Println("Can't read file:", input_files[0], "Error:", err)
		} else {
			fmt.Println("Output file content is(like string type):\n", string(content)) //string Output
			fmt.Println("Output file content is(like byte type):\n", content) //bytes Output
		}
	}
}

Args保存命令行参数,包括命令本身作为Args[0]。如果Args字段为空或nil,Run使用{Path}。在典型用法中,通过调用Command来设置Path和Args。Args []string函数。此函数返回字符串类型的数组https://golang.org/pkg/os/exec/。Args保存命令行参数,从程序名称开始。在这种情况下,从命令行获取文件名的简便方法是使用os.Args[1:]。以下是输出示例:

elshan_abd$ go run main.go abc.txt
Hi guys  ('-')
File_name is: abc.txt
Output file content is(like string type):
aaa
bbb
ccc
1234
Output file content is(like byte type):
[97 97 97 10 98 98 98 10 99 99 99 10 49 50 51 52 10]

最后,我们需要使用以下函数来读取文件内容:func ReadFile(filename string) ([]byte, error),源代码位于https://golang.org/pkg/io/ioutil/#ReadFile

英文:

For running .go file from command-line by input parameter like file (for example abc.txt).We need use mainly os, io/ioutil, fmt packages. Additionally for reading command line parameters we use
os.Args Here is example code

package main
 import (
  &quot;fmt&quot;
  &quot;os&quot;
  &quot;io/ioutil&quot;
)
func main()  {
fmt.Println(&quot; Hi guys  (&#39;-&#39;) &quot;)
input_files := os.Args[1:]
//input_files2 := os.Args[0];
//fmt.Println(&quot;if2 : &quot;,input_files2)
if len(input_files) &lt; 1{
fmt.Println(&quot;Not detected files.&quot;)
}else{
fmt.Println(&quot;File_name is : &quot;,input_files[0])
content, err := ioutil.ReadFile(input_files[0])
if err != nil {
fmt.Println(&quot;Can&#39;t read file :&quot;, input_files[0],&quot;Error : &quot;,err)
}else {
fmt.Println(&quot;Output file content is(like string type) : \n&quot;,string(content))//string Output
fmt.Println(&quot;Output file content is(like byte type) : \n&quot;,content)//bytes Output
}
}
}

Args holds command line arguments, including the command as Args[0].
If the Args field is empty or nil, Run uses {Path}.
In typical use, both Path and Args are set by calling Command.
Args []string
function. This function return back array on string type https://golang.org/pkg/os/exec/.Args hold the command-line arguments, starting with the program name. In this case short way to take filename from command-line is this functions os.Args[1:] . And here is output

elshan_abd$ go run main.go abc.txt
Hi guys  (&#39;-&#39;)
File_name is :  abc.txt
Output file content is(like string type) : 
aaa
bbb
ccc
1234
Output file content is(like byte type) : 
[97 97 97 10 98 98 98 10 99 99 99 10 49 50 51 52 10] 

Finally we need for reading content file this function
func ReadFile(filename string) ([]byte, error) source is https://golang.org/pkg/io/ioutil/#ReadFile

huangapple
  • 本文由 发表于 2016年1月29日 16:38:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/35080109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定