Read text file, and print out the result

Hi,

I have three different packages in which I have structs, so I am trying to create a program that reads a file and calls the specific func when the line starts with the specific number. For example, program should call Function A when line starts with “1” and then go to the next line and call function B if line starts with “2”. Can someone plz help me with this type of code?

What have you tried so far? You should be able to open a file via os.Open and scan your file line by line with a bufio.Scanner. There are some examples of using a Scanner here.

This is what I have so far, so in this program I am reading the first line to see if it starts with “1” and if it does then I am calling another function.

package main

import (
“bufio”
//“fmt”
pack “package”
“log”
“os”
)

func main() {
file, err := os.Open(“file path”)

if err != nil {
	log.Fatalf("failed opening file: %s", err)
}

scanner := bufio.NewScanner(file)
fileLineNumber := 0

scanner.Scan()
line := scanner.Text()
linenumber++
var val pack1 = func1
if line[0] == '1' {
	val, err = pack.func2(line)
	log.Fatal("The first line of the file is", val)
} else {
	log.Fatal("Invalid file - " + line + "\n")
}

Thanks for elaborating. And your current problem is having it read the entire file instead of just the first line? If so, you can use a for loop. Quick example (you might want to also check for things like empty lines):

for scanner.Scan() {
    line := scanner.Text()
    switch line[0] {
    case '1':
        // call function A
    case '2':
        // call function B
    default:
        // default case
    }
}
4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.