title: How to delete the contents of a file before writing to it?
body: <p>I wrote a bot that performs some network queries once every so often and dumps the latest state into a file stored on disk. This is my code:</p>
  <pre class="lang-rust prettyprint-override"><code>let log_file = OpenOptions::new()
      .read(true)
      .write(true)
      .create(true)
      .open(&amp;log_file_name)
      .unwrap();
  serde_json::to_writer(
      log_file,
      &amp;State {
          foo: self.foo,
          bar: self.bar
      },
  )
  .unwrap();
  </code></pre>
  <p>The issue is that, occasionally, the size of the newest state json will be smaller than the size of the previous state JSON. This leaves that portion of the previous state JSON that is longer than the new state JSON to remain in the log file:</p>
  <pre class="lang-json prettyprint-override"><code>{&quot;foo&quot;: 1,&quot;bar&quot;: 2}&quot;baz&quot;: 3}
  </code></pre>
  <p>In the example above, <code>&quot;baz&quot;: 3}</code> is the leftover data from the previous state JSON.</p>
  <p>The question is: how can I rewrite the code so that I first flush all the contents of the file and then write the new state json?</p>
  <p>I know deleting the file is a solution but I would prefer not to do that.</p>