fix: strip trailing empty line when reading files
Updated the ReadFile function in 'utilities' by using the Scanner from the bufio package to read lines from a text file. The trailing empty line is stripped after scanning and before returning back to the caller.
This commit is contained in:
parent
eb016b96e9
commit
4e76d20a7a
1 changed files with 21 additions and 3 deletions
|
@ -1,18 +1,36 @@
|
|||
package utilities
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func ReadFile(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unable to read the data from the file: %w", err)
|
||||
return "", fmt.Errorf("unable to open %q: %w", path, err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
var lines []string
|
||||
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
|
||||
return string(data), nil
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", fmt.Errorf("received an error after scanning the contents from %q: %w", path, err)
|
||||
}
|
||||
|
||||
if lines[len(lines)-1] == "" {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
|
||||
return strings.Join(lines, "\n"), nil
|
||||
}
|
||||
|
||||
func FileExists(path string) (bool, error) {
|
||||
|
|
Loading…
Reference in a new issue