Home > Mobile >  go program takes the file in and have to spit out to STARDARD OUTPUT
go program takes the file in and have to spit out to STARDARD OUTPUT

Time:09-14

have go lang program that takes file in and adds data to it then needs to writed out to standard out. I got everything except writing out to standard output. I'm new to programming so i need explanation and solution so i can undestand.


)

type Event struct {
        Specversion string    `json:"specversion"`
        ID          uuid.UUID `json:"id"` /// uuid
        Source      string    `json:"source"`
        Type        string    `json:"type"`
        Time        time.Time `json:"time"`
        Data        string    `json:"data"` /// this part supposed to come from the file
}

type Data struct {
        MacAddress            string            `json:"mac_address"`
        SerialNumber          string            `json:"serial_number"`
        DeviceType            string            `json:"device_type"`
        DeviceModel           string            `json:"device_model"`
        PartNumber            string            `json:"part_number"`
        ExtraAttributes       []DeviceAttribute `json:"extra_attributes"`
        PlatformCustomerID    string            `json:"platform_customer_id"`
        ApplicationCustomerID string            `json:"application_customer_id"`
}

type DeviceAttribute struct {
        AttributeType  string `json:"attribute_type"`
        AttributeValue string `json:"attribute_value"`
}

var replacer = strings.NewReplacer("\r", "", "\n", "")

func main() {

        if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
                fmt.Println("Usage : "   os.Args[0]   " file name")
                help()
                os.Exit(1)
        }

        Data, err := ioutil.ReadFile(os.Args[1])
        if err != nil {
                fmt.Println("Cannot read the file or file does not exists")
                os.Exit(1)
        }

        data := replacer.Replace(string(Data))

        e := Event{
                Specversion: "1.0",
                ID:          uuid.New(),
                Source:      "CSS",
                Type:        "", //  user input -p or -u,
                Time:        time.Now(),
                Data:        data,
        }

        out, _ := json.MarshalIndent(e, "", "")
        fmt.Println(string(out))
}

func help() {
        fmt.Println("help")
}

go playground

CodePudding user response:

os.WriteFile

if err := os.WriteFile("something.json", out, 0644); err != nil {
    log.Fatal(err)
}

or in bash:

How to redirect and append both standard output and standard error to a file with Bash

Redirect all output to file in Bash


Also consider using the built-in flag library.

CodePudding user response:

fmt.Print and friends (fmt.Println and fmt.Printf) write to os.Stdout.

So you're already writing your results out:

        out, _ := json.MarshalIndent(e, "", "")
        fmt.Println(string(out))

You might consider writing error messages to standard error so they don't get confused with standard out:

                fmt.Fprintln(os.Stderr, "Cannot read the file or file does not exists")
                os.Exit(1)

how you redirect to to a file?

When you run your program you can specify a redirect in the shell:

go build
./my-program > results.txt

The shell will open results.txt O_CREAT|O_TRUNC and connect that open file to your program's standard output stream. In this case, you won't see the standard output on the terminal because it's going into the file instead.

If you want to see the standard output that's being read to a file, you can pipe the output to tee instead of a file:

./my-program | tee results.txt

tee is a program the reads its standard input, and writes it to both its standard output and the specified file. In that invocation, the shell creates a pipe, connects the pipe's input end to my-program's standard output, and connects the pipe's output to tee's standard input before executing my-program and tee.

This way you can create a "pipeline" of commands, using the output of one as the input of the next, to describe complex tasks as a combination of simple operations. By writing to stdout in your programs, you give the user control over exactly what stdout is.

  • Related