Hello Everybody
I just wanna learn how can i read desired line from the file ?
e.g
I wanna read third line from the file
How can i do ?
Please help me
Hello Everybody
I just wanna learn how can i read desired line from the file ?
e.g
I wanna read third line from the file
How can i do ?
Please help me
arquivo.txt
First line
Second line
Third line
main.go
package main
import (
"os"
"io/ioutil"
"strings"
"fmt"
)
func main() {
fileIO, err := os.OpenFile("arquivo.txt", os.O_RDWR, 0600)
if err != nil {
panic(err)
}
defer fileIO.Close()
rawBytes, err := ioutil.ReadAll(fileIO)
if err != nil {
panic(err)
}
lines := strings.Split(string(rawBytes), "\n")
for i, line := range lines {
if i == 2 {
fmt.Println(line)
}
}
}
Why we use (os.O_RDWR,0600)
Sorry for this question because i am new at this languege
Thank for helping
constant O_RDWR and 0600 permission of file, as the constants below
// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
)
Thank you for helping
Have a good day
Use os.Open instead
It would be preferable to read a file using a buffered scanner and reading line by line, rather than using ioutil.ReadAll
and reading the whole file into memory just to read a single line.
Also as @dfc has suggested, definitely use os.Open
rather than os.OpenFile
for this case.
Anyway here’s a simple example to print the 3rd line from a file:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
var line int
for scanner.Scan() {
if line == 2 {
fmt.Println(scanner.Text())
}
line++
}
if err := scanner.Err(); err != nil {
log.Fatalln(err)
}
}
Although keeping in mind that for only reading the third line in a file, if you know that it’s going to be a small file, then reading it all into memory might be better, but for reading say the third line from a large file, it wouldn’t be ideal.
Thank you for helping
No worries
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.