Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bufio: scanner does not work if you pass a structure item as an argument #52420

Closed
michail-vestnik opened this issue Apr 19, 2022 · 1 comment

Comments

@michail-vestnik
Copy link

What version of Go are you using (go version)?

$ go version: go1.17 linux/amd64

Does this issue reproduce with the latest release?

Yes

Example code

I wrote a code example that demonstrates the problem well.

package main

import (
	"bufio"
	"fmt"
	"os"
)

type Example struct {
	file *os.File
}

func NewExample() *Example {

	f, _ := os.OpenFile("./fakedata.txt", os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644)
        // fakedata.txt is a text file that contains three lines:
        // string 01
        // string 02
        // string 03

	ex := Example{
		file: f,
	}

	fmt.Printf("example.file 01: %v\n", &ex.file)

	scanner := bufio.NewScanner(ex.file)
	fmt.Println(scanner.Err())

	for scanner.Scan() {
		fmt.Printf("scanner.Text 01(): %v\n", scanner.Text())
	}

	return &ex

}

func (ex *Example) Scan() {

	fmt.Printf("example.file 02: %v\n", &ex.file) // same address!

	scanner := bufio.NewScanner(ex.file)
	fmt.Println(scanner.Err())

	for scanner.Scan() {
		fmt.Printf("scanner.Text 02(): %v\n", scanner.Text())
	}

}

func main() {

	example := NewExample()
	/*
		scanner.Text_01(): string 01
		scanner.Text_01(): string 02
		scanner.Text_01(): string 03
	*/

	example.Scan()
	// nothing

}

Why doesn't the scanner work if you pass it a file as a structure element, given the same address in memory?

Thanks/

@robpike
Copy link
Contributor

robpike commented Apr 19, 2022

You need to reopen the file. Your call to example.Scan is using the same file descriptor and it's already at EOF.

@robpike robpike closed this as completed Apr 19, 2022
@golang golang locked and limited conversation to collaborators Apr 19, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants