I'm unable to find file.ReadLine
function in Go. I can figure out how to quickly write one, but just wondering if I'm overlooking something here. How does one read a file line by line?
相关问题
- Correctly parse PDF paragraphs with Python
- how to split a list into a given number of sub-lis
- What is the best way to do a search in a large fil
- Generate string from integer with arbitrary base i
- R: eval(parse()) error message: cannot ope
相关文章
- Can I run a single test in a suite?
- JSP String formatting Truncate
- Selecting only the first few characters in a strin
- How do I get from a type to the TryParse method?
- How to check if a request was cancelled
- What is the correct way to declare and use a FILE
- Is it possible to implement an interface with unex
- Python: print in two columns
Use:
reader.ReadString('\n')
\n
at the end of the string returned.reader.ReadLine()
I tested the various solutions suggested by writing a program to test the scenarios which are identified as problems in other answers:
I found that:
Scanner
solution does not handle long lines.ReadLine
solution is complex to implement.ReadString
solution is the simplest and works for long lines.Here is code which demonstrates each solution, it can be run via
go run main.go
:I tested on:
The test program outputs:
NOTE: The accepted answer was correct in early versions of Go. See the highest voted answer contains the more recent idiomatic way to achieve this.
There is function ReadLine in package
bufio
.Please note that if the line does not fit into the read buffer, the function will return an incomplete line. If you want to always read a whole line in your program by a single call to a function, you will need to encapsulate the
ReadLine
function into your own function which callsReadLine
in a for-loop.bufio.ReadString('\n')
isn't fully equivalent toReadLine
becauseReadString
is unable to handle the case when the last line of a file does not end with the newline character.bufio.Reader.ReadLine() works well. But if you want to read each line by a string, try to use ReadString('\n'). It doesn't need to reinvent the wheel.
I like Lzap solution, I am new in Go, I woud like to ask to lzap but I could not do it I have not 50 points yet.. I change a little your solution and complete the code...
I am not sure why I need to test 'err' again, but in anyway we can do it. But, the main question is.. why Go do not produce error with the sentence => line, err := r.ReadString(10), inside the loop ? It is defined again and again each time the loop is executed. I avoid that situation with my change, any comment? I set the condition EOF in the 'for' as similar to a While too. Thanks
In the code bellow, I read the interests from the CLI until the user hits enter and I'm using Readline:
Here is an example with function
ReadFromStdin()
it's likefmt.Scan(&name)
but its takes all strings with blank spaces like: "Hello My Name Is ..."