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

core -> filex-> file.go -> firstLine has error #4217

Closed
Owen-Zhang opened this issue Jun 27, 2024 · 2 comments
Closed

core -> filex-> file.go -> firstLine has error #4217

Owen-Zhang opened this issue Jun 27, 2024 · 2 comments

Comments

@Owen-Zhang
Copy link

Owen-Zhang commented Jun 27, 2024

发现两个问题:

  1. 如果内容为空(什么都没有,包括没有\n\r什么的),程序会出现死 loop, 如果 if n== 0 { return string(first), nil }
  2. 没有对前端有空行(\r\n, \n, \t)这些字节进行处理, 如果前面有空行,返回的第一行数据有问题
  3. lastline也有同样的问题

firstline 下面这样怎么样

func FirstLine(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	firstLine := ""
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		temp := scanner.Text()
		if len(temp) == 0 {
			continue
		}
		firstLine = temp
		break
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
        return firstLine, nil
}
@JiChenSSG
Copy link
Contributor

The problem actually exist. Emprt content cause infinite loop in Firstline read, and raise panic in Lastline. I thing empty file should return "". Maybe I can try to fix this.

问题确实存在。空内容导致 Firstline 读取时出现无限循环,Lastline 读取时出现 panic。我认为空文件应该返回 ""。也许我可以尝试修复这个问题。

报错信息:
`panic: runtime error: index out of range [-1] [recovered]
panic: runtime error: index out of range [-1]

goroutine 6 [running]:
testing.tRunner.func1.2({0x5d0600, 0xc00001a258})
/home/jichen/libs/go/src/testing/testing.go:1631 +0x24a
testing.tRunner.func1()
/home/jichen/libs/go/src/testing/testing.go:1634 +0x377
panic({0x5d0600?, 0xc00001a258?})
/home/jichen/libs/go/src/runtime/panic.go:770 +0x132
github.com/zeromicro/go-zero/core/filex.lastLine({0xc00001e600?, 0x2f?}, 0xc0000760e8)
/home/jichen/code/go-zero/core/filex/file.go:77 +0x269
github.com/zeromicro/go-zero/core/filex.LastLine({0xc00001e600, 0x2f})
/home/jichen/code/go-zero/core/filex/file.go:29 +0xa6
github.com/zeromicro/go-zero/core/filex.TestLastLineEmptyFile(0xc0000d0820)
/home/jichen/code/go-zero/core/filex/file_test.go:143 +0xb5
testing.tRunner(0xc0000d0820, 0x612490)
/home/jichen/libs/go/src/testing/testing.go:1689 +0xfb
created by testing.(*T).Run in goroutine 1
/home/jichen/libs/go/src/testing/testing.go:1742 +0x390
FAIL github.com/zeromicro/go-zero/core/filex 0.005s`

@kevwan
Copy link
Contributor

kevwan commented Jul 20, 2024

fixed by #4258

@kevwan kevwan closed this as completed Jul 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants