Created
December 3, 2019 11:48
-
-
Save kevsersrca/254c57d33a71da70fc1b297b169d70fb to your computer and use it in GitHub Desktop.
Get File Eleman in file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// n = file line number | |
func getLine(filename string, n int) (string, error) { | |
if n < 1 { | |
return "", fmt.Errorf("invalid request: line %d", n) | |
} | |
f, err := os.Open(filename) | |
if err != nil { | |
return "", err | |
} | |
defer f.Close() | |
bf := bufio.NewReader(f) | |
var line string | |
for lnum := 0; lnum < n; lnum++ { | |
line, err = bf.ReadString('\n') | |
if err == io.EOF { | |
switch lnum { | |
case 0: | |
return "", errors.New("no lines in file") | |
case 1: | |
return "", errors.New("only 1 line") | |
default: | |
return "", fmt.Errorf("only %d lines", lnum) | |
} | |
} | |
if err != nil { | |
return "", err | |
} | |
} | |
if line == "" { | |
return "", fmt.Errorf("line %d empty", n) | |
} | |
return line, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment