简体   繁体   中英

How to merge or combine 2 files into single file

I need to take tmp1.zip and append it's tmp1.signed file to the end of it; creating a new tmp1.zip.signed file using Go. It's essentially same as cat | sc I could call cmd line from Go, but that seems super inefficient (and cheesy).

So far

Google-ing the words "go combine files" et. al. yields minimal help.

But I have come across a couple of options that I have tried such as ..

    f, err := os.OpenFile("tmp1.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Fatal(err)
}
if _, err := f.Write([]byte("appended some data\n")); err != nil {
    log.Fatal(err)
}
if err := f.Close(); err != nil {
    log.Fatal(err)
}

But that is just getting strings added to the end of the file, not really merging the two files, or appending the signature to the original file.

Question

Assuming I am asking the right questions to get one file appended to another, Is there a better sample of how exactly to merge two files into one using Go?

Based on your question, you want to create a new file with the content of both files.

You can use io.Copy to achieve that.

Here is a simple command-line tool implementing it.

package main

import (
    "io"
    "log"
    "os"
)

func main() {
    if len(os.Args) != 4 {
        log.Fatalln("Usage: %s <zip> <signed> <output>\n", os.Args[0])
    }
    zipName, signedName, output := os.Args[1], os.Args[2], os.Args[3]

    zipIn, err := os.Open(zipName)
    if err != nil {
        log.Fatalln("failed to open zip for reading:", err)
    }
    defer zipIn.Close()

    signedIn, err := os.Open(signedName)
    if err != nil {
        log.Fatalln("failed to open signed for reading:", err)
    }
    defer signedIn.Close()

    out, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatalln("failed to open outpout file:", err)
    }
    defer out.Close()

    n, err := io.Copy(out, zipIn)
    if err != nil {
        log.Fatalln("failed to append zip file to output:", err)
    }
    log.Printf("wrote %d bytes of %s to %s\n", n, zipName, output)

    n, err = io.Copy(out, signedIn)
    if err != nil {
        log.Fatalln("failed to append signed file to output:", err)
    }
    log.Printf("wrote %d bytes of %s to %s\n", n, signedName, output)
}

Basically, it open both files you want to merge, create a new one and copy the content of each file to the new file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM