Sienna
Sienna

Reputation: 1699

Golang: write marshal xml to file

I have a byte array of marshalled XML, if I write it to a file using the os library:

fh, _ := os.OpenFile("filename", os.O_CREATE, 0644)
_, err := fh.Write(XMLByteArray)

I get a bunch of junk at the end of the file as if it was a bad write:

<project version="4">
  <component name="test">
    <option name="urls">
      <list></list>
    </option>
  </component>
</project>    </option>
  </component>
</project>on>
            </component>
    </project>

If I write it with io/ioutil library like this:

err = ioutil.WriteFile("filename", XMLByteArray, 0644)
    if err != nil {
        log.Fatal(err)
    }

I get proper XML:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="test">
    <option name="urls">
      <list></list>
    </option>
  </component>
</project>

Here's the part I really don't understand. This file is the result of a dynamic path generation, and is the configuration for IntelliJ. If I use os.Write() and then properly close the file handler, IntelliJ reads the file immediately, but errors out because the XML is messed up. If I write the file with ioutil.WriteFile(), the file looks correct, but IntelliJ isn't recognising the file to exist.

So my questions are:

  1. What is the difference between os.Write() and ioutil.WriteFile()?
  2. Why is that difference causing the byte array to be written differently?

Upvotes: 0

Views: 649

Answers (1)

Mark
Mark

Reputation: 7101

In the OpenFile call, the file already exists and is being reopened and not truncated. The data written is smaller than the content of the file, so overwrites only the start of the file, leaving junk at the end.

According to os flags you can truncate the file upon opening:

os.OpenFile("filename", os.O_CREATE | os.O_TRUNC, 0644)

Or use os.Create().

This is basically what iotuil.WriteFile is doing (see source).

IntelliJ might not be able to open the file if it doesn't have sufficient permissions. Try changing permissions to 0666 in the code, and check the file is created with these permissions. Note the permission parameter is ignored if the file already exists. Also, the permissions set when creating a file may be restricted by the umask of the process.

Upvotes: 2

Related Questions