Skip to content

Commit bcdda1b

Browse files
authored
Update add read file methods
1 parent dcc1ab0 commit bcdda1b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

files/files.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,33 @@ func (f *Files) FileExists(filePath string) bool {
198198
func (f *Files) RemoveAllDir(dirPath string) error {
199199
return os.RemoveAll(dirPath)
200200
}
201+
202+
// ReadFile reads and returns the entire content of a file specified by filePath as a string.
203+
func (f *Files) ReadFile(filePath string) (string, error) {
204+
data, err := os.ReadFile(filePath)
205+
if err != nil {
206+
return "", err
207+
}
208+
return string(data), nil
209+
}
210+
211+
// ReadFileByLine reads and returns the contents of a file specified by filePath line by line as a slice of strings.
212+
func (f *Files) ReadFileByLine(filePath string) ([]string, error) {
213+
file, err := os.Open(filePath)
214+
if err != nil {
215+
return nil, err
216+
}
217+
defer file.Close()
218+
219+
var lines []string
220+
scanner := bufio.NewScanner(file)
221+
for scanner.Scan() {
222+
lines = append(lines, scanner.Text())
223+
}
224+
225+
if err := scanner.Err(); err != nil {
226+
return nil, err
227+
}
228+
229+
return lines, nil
230+
}

0 commit comments

Comments
 (0)