This commit is contained in:
nlohmann committed 2026-11-04 18:25:25 +00:00
1 parent 264aee6773
commit 15ab5fa5c1
449 files changed
+1558 -1190

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=description content="JSON for Modern C++ is a header-only C++11 library that makes JSON a first-class data type."><meta name=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/files/" rel="canonical"><link href=../element_access/default_value/ rel=prev><link href=../iterators/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.8.0"><title>Reading and writing files - JSON for Modern C++</title><link rel=stylesheet href=../../assets/stylesheets/main.57a0d79d.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.fb2fffe2.min.css><link rel=stylesheet href=../../css/custom.css><link rel=stylesheet href=../../css/brand.css><link rel=stylesheet href=../../css/fig-sax.css><link rel=stylesheet href=../../css/fig-jsonview.css><link rel=stylesheet href=../../css/fig-exceptions.css><link rel=stylesheet href=../../css/fig-pointer.css><link rel=stylesheet href=../../css/fig-charts.css><link rel=stylesheet href=../../css/fig-integration.css><link rel=stylesheet href=../../css/fig-macros.css><script>__md_scope=new URL("../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#reading-and-writing-files class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../.. title="JSON for Modern C++" class="md-header__button md-logo" aria-label="JSON for Modern C++" data-md-component=logo> <img src=../../images/wordmark-header.svg alt=logo> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> JSON for Modern C++ </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Reading and writing files </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media="(prefers-color-scheme: light)" data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media="(prefers-color-scheme: dark)" data-md-color-scheme=slate data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent")}for(var[key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script> <label class="md-header__button md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0Line truncated
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;stdexcept&gt;</span>
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;string&gt;</span>
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;nlohmann/json.hpp&gt;</span>
<span class=k>using</span><span class=w> </span><span class=n>json</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=p>;</span>
<span class=n>json</span><span class=w> </span><span class=nf>read_json_file</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>&amp;</span><span class=w> </span><span class=n>path</span><span class=p>)</span>
<span class=p>{</span>
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>ifstream</span><span class=w> </span><span class=n>f</span><span class=p>(</span><span class=n>path</span><span class=p>);</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=o>!</span><span class=n>f</span><span class=p>.</span><span class=n>is_open</span><span class=p>())</span>
<span class=w> </span><span class=p>{</span>
<span class=w> </span><span class=k>throw</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>runtime_error</span><span class=p>(</span><span class=s>"cannot open "</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=n>path</span><span class=p>);</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=k>return</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>f</span><span class=p>);</span>
<span class=p>}</span>
</code></pre></div> <ul> <li><strong>Check that the file is open.</strong> A stream that failed to open looks like an empty input, so <code>parse</code> reports <a href=../../home/exceptions/#jsonexceptionparse_error101><code>parse_error.101</code></a> ("unexpected end of input") at line 1, column 1 instead of saying that the file is missing. A relative path is resolved against the working directory of the running program, which is often not the directory of the source file (see the <a href=../../home/faq/#parsing-a-file-fails-with-unexpected-end-of-input><abbr title="Frequently Asked Questions">FAQ</abbr></a>).</li> <li><strong>Don't read the file into a string first.</strong> Parsing from a <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>ifstream</span></code> is only about 10 to 20 % slower than reading the whole file into a string with one <code>read()</code> and parsing that, and it needs no memory for the copy (see <a href=../parsing/#input-sources-and-performance>input sources and performance</a>). The common way to read a file with <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>istreambuf_iterator</span><span class=o>&lt;</span><span class=kt>char</span><span class=o>&gt;</span></code> is so slow that it takes about twice as long as parsing from the stream. Read the file into a string only if you need the text itself, for example for an error message. This advice is for <code class=highlight><span class=n>json</span><span class=o>::</span><span class=n>parse</span></code>. <a href=../json_view/ ><code>json_document</code></a> reads a stream into a buffer that it owns anyway, so there is no copy to save: reading the file into a <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code> yourself and passing that as an lvalue, which the document borrows, was about 6 to 12 % faster than parsing from the stream, with the same single buffer.</li> <li><code>parse</code> requires the file to hold exactly one <abbr title="JavaScript Object Notation">JSON</abbr> value. Files with one value per line are read with <a href=../parsing/json_lines/ ><abbr title="JavaScript Object Notation">JSON</abbr> Lines</a>; files too large for memory are covered in <a href=../parsing/large_and_partial_input/ >Large, streamed, and partial input</a>.</li> </ul> <h2 id=writing-a-json-file>Writing a <abbr title="JavaScript Object Notation">JSON</abbr> file<a class=headerlink href=#writing-a-json-file title="Permanent link">&para;</a></h2> <p><a href=../../api/basic_json/dump/ ><code>dump</code></a> the value into a string first, then write the string:</p> <div class=highlight><pre><span></span><code><span class=kt>void</span><span class=w> </span><span class=nf>write_json_file</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>&amp;</span><span class=w> </span><span class=n>path</span><span class=p>,</span><span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>json</span><span class=o>&amp;</span><span class=w> </span><span class=n>j</span><span class=p>)</span>
<span class=p>{</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=w> </span><span class=n>text</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>dump</span><span class=p>(</span><span class=mi>4</span><span class=p>)</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span><span class=w> </span><span class=c1>// may throw: nothing is written yet</span>
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>ofstream</span><span class=w> </span><span class=n>f</span><span class=p>(</span><span class=n>path</span><span class=p>,</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>ios</span><span class=o>::</span><span class=n>binary</span><span class=p>);</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=o>!</span><span class=n>f</span><span class=p>.</span><span class=n>is_open</span><span class=p>())</span>
<span class=w> </span><span class=p>{</span>
<span class=w> </span><span class=k>throw</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>runtime_error</span><span class=p>(</span><span class=s>"cannot open "</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=n>path</span><span class=p>);</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=n>f</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>text</span><span class=p>;</span>
<span class=w> </span><span class=n>f</span><span class=p>.</span><span class=n>close</span><span class=p>();</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=n>f</span><span class=p>.</span><span class=n>fail</span><span class=p>())</span>
<span class=w> </span><span class=p>{</span>
<span class=w> </span><span class=k>throw</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>runtime_error</span><span class=p>(</span><span class=s>"cannot write "</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=n>path</span><span class=p>);</span>
<span class=w> </span><span class=p>}</span>
<span class=p>}</span>
</code></pre></div> <ul> <li><strong>Serialize before opening the file.</strong> Opening a <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>ofstream</span></code> truncates the file. <code>dump</code> and <a href=../../api/operator_ltlt/ ><code>operator&lt;&lt;</code></a> throw <a href=../../home/exceptions/#jsonexceptiontype_error316><code>type_error.316</code></a> when a string is not valid <abbr title="Unicode Transformation Format">UTF</abbr>-8 (see <a href=../serialization/#handling-invalid-utf-8>handling invalid <abbr title="Unicode Transformation Format">UTF</abbr>-8</a>), and <code class=highlight><span class=n>f</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>setw</span><span class=p>(</span><span class=mi>4</span><span class=p>)</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>j</span></code> may already have written part of the value when it throws. Serializing into a string first leaves the old file untouched in that case.</li> <li><strong>Check the stream after closing it.</strong> A full disk or a missing permission sets the stream's error state; it does not throw unless you enabled exceptions on the stream with <code>exceptions()</code>.</li> <li><code>std::ios::binary</code> writes the text as it is. Without it, Windows writes <code>\r\n</code> for every newline of a pretty-printed value.</li> </ul> <h2 id=replacing-a-file-without-corrupting-it>Replacing a file without corrupting it<a class=headerlink href=#replacing-a-file-without-corrupting-it title="Permanent link">&para;</a></h2> <p>The library never writes a file itself, so this section is not about the library. It is general C++ advice for a problem users of the library keep running into.</p> <p>A program that crashes or is killed while it writes leaves a truncated file behind. To make sure readers see either the old or the new contents, write to a temporary file in the same directory and rename it over the original (C++17, <code class=highlight><span class=o>&lt;</span><span class=n>filesystem</span><span class=o>&gt;</span></code>):</p> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;filesystem&gt;</span>
<span class=kt>void</span><span class=w> </span><span class=nf>replace_json_file</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>filesystem</span><span class=o>::</span><span class=n>path</span><span class=o>&amp;</span><span class=w> </span><span class=n>path</span><span class=p>,</span><span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>json</span><span class=o>&amp;</span><span class=w> </span><span class=n>j</span><span class=p>)</span>
<span class=p>{</span>
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>filesystem</span><span class=o>::</span><span class=n>path</span><span class=w> </span><span class=n>tmp</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>path</span><span class=p>;</span>
<span class=w> </span><span class=n>tmp</span><span class=w> </span><span class=o>+=</span><span class=w> </span><span class=s>".tmp"</span><span class=p>;</span><span class=w> </span><span class=c1>// use a unique name if several processes may write the file</span>
<span class=w> </span><span class=n>write_json_file</span><span class=p>(</span><span class=n>tmp</span><span class=p>.</span><span class=n>string</span><span class=p>(),</span><span class=w> </span><span class=n>j</span><span class=p>);</span>
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>filesystem</span><span class=o>::</span><span class=n>rename</span><span class=p>(</span><span class=n>tmp</span><span class=p>,</span><span class=w> </span><span class=n>path</span><span class=p>);</span><span class=w> </span><span class=c1>// replaces path</span>
<span class=p>}</span>
</code></pre></div> <p>The temporary file must be in the same directory (more precisely, on the same file system) as the target: a rename across file systems does not fall back to a copy, it fails and throws <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>filesystem</span><span class=o>::</span><span class=n>filesystem_error</span></code>. On POSIX systems, the rename atomically replaces the file. Standard C++ has no way to flush a file to the disk (<code>fsync</code>), so this protects against a crashed program, but not necessarily against a power loss.</p> <h2 id=binary-formats>Binary formats<a class=headerlink href=#binary-formats title="Permanent link">&para;</a></h2> <p>The <a href=../binary_formats/ >binary formats</a> work the same way, with the streams opened in binary mode:</p> <div class=highlight><pre><span></span><code><span class=c1>// read</span>
<span class=n>std</span><span class=o>::</span><span class=n>ifstream</span><span class=w> </span><span class=n>in</span><span class=p>(</span><span class=s>"data.cbor"</span><span class=p>,</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>ios</span><span class=o>::</span><span class=n>binary</span><span class=p>);</span>
<span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>from_cbor</span><span class=p>(</span><span class=n>in</span><span class=p>);</span>
<span class=c1>// write</span>
<span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o>&lt;</span><span class=n>std</span><span class=o>::</span><span class=kt>uint8_t</span><span class=o>&gt;</span><span class=w> </span><span class=n>bytes</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>to_cbor</span><span class=p>(</span><span class=n>j</span><span class=p>);</span>
<span class=n>std</span><span class=o>::</span><span class=n>ofstream</span><span class=w> </span><span class=n>out</span><span class=p>(</span><span class=s>"data.cbor"</span><span class=p>,</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>ios</span><span class=o>::</span><span class=n>binary</span><span class=p>);</span>
<span class=n>out</span><span class=p>.</span><span class=n>write</span><span class=p>(</span><span class=k>reinterpret_cast</span><span class=o>&lt;</span><span class=k>const</span><span class=w> </span><span class=kt>char</span><span class=o>*&gt;</span><span class=p>(</span><span class=n>bytes</span><span class=p>.</span><span class=n>data</span><span class=p>()),</span><span class=w> </span><span class=k>static_cast</span><span class=o>&lt;</span><span class=n>std</span><span class=o>::</span><span class=n>streamsize</span><span class=o>&gt;</span><span class=p>(</span><span class=n>bytes</span><span class=p>.</span><span class=n>size</span><span class=p>()));</span>
</code></pre></div> <p>Without <code>std::ios::binary</code>, Windows turns the bytes <code>0x0D 0x0A</code> into <code>0x0A</code> and may stop at a byte <code>0x1A</code> while reading, and turns <code>0x0A</code> into <code>0x0D 0x0A</code> while writing, which corrupts the data.</p> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">&para;</a></h2> <ul> <li><a href=../parsing/ >Parsing</a> - the inputs <code>parse</code> accepts</li> <li><a href=../serialization/ >Serialization</a> - the options of <code>dump</code></li> <li><a href=../../api/basic_json/parse/ ><code>parse</code></a>, <a href=../../api/basic_json/dump/ ><code>dump</code></a></li> <li><a href=../../api/operator_gtgt/ ><code>operator&gt;&gt;</code></a>, <a href=../../api/operator_ltlt/ ><code>operator&lt;&lt;</code></a></li> </ul> <!-- https://squidfunk.github.io/mkdocs-material/reference/tooltips/#adding-a-glossary --> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date" title="November 4, 2026 16:46:20 UTC">November 4, 2026</span> </span> </aside> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var labels=set.querySelector(".tabbed-labels");for(var tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <nav class="md-footer__inner md-grid" aria-label=Footer> <a href=../element_access/default_value/ class="md-footer__link md-footer__link--prev" aria-label="Previous: Access with default value: value"> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg> </div> <div class=md-footer__title> <span class=md-footer__direction> Previous </span> <div class=md-ellipsis> Access with default value: value </div> </div> </a> <a href=../iterators/ class="md-footer__link md-footer__link--next" aria-label="Next: Iterators"> <div class=md-footer__title> <span class=md-footer__direction> Next </span> <div class=md-ellipsis> Iterators </div> </div> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11z"/></svg> </div> </a> </nav> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> <div class=md-copyright__highlight> Copyright &copy; 2013-2026 Niels Lohmann </div> </div> <div class=md-social> <a href="https://github.com/nlohmann" target="_blank" rel="noopener" title="github.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 512 512"><!-- Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2025 Fonticons, Inc.--><path d="M173.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6m-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3m44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9M252.8 8C114.1 8 8 113.3 8 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C436.2 457.8 504 362.9 504 252 504 113.3 391.5 8 252.8 8M105.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1m-10.8-8.1Line truncated
+102
View File
@@ -0,0 +1,102 @@
# Reading and writing files
The library has no functions that take a file name. It reads from and writes to streams, so files are handled with `std::ifstream` and `std::ofstream` (or a `FILE*` when reading). This page collects the recipes for the common cases and the mistakes that show up again and again.
## Reading a JSON file
Pass the stream to [`parse`](https://json.nlohmann.me/api/basic_json/parse/index.md) directly, and check that the file was opened:
```
#include <fstream>
#include <stdexcept>
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json read_json_file(const std::string& path)
{
std::ifstream f(path);
if (!f.is_open())
{
throw std::runtime_error("cannot open " + path);
}
return json::parse(f);
}
```
- **Check that the file is open.** A stream that failed to open looks like an empty input, so `parse` reports [`parse_error.101`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error101) ("unexpected end of input") at line 1, column 1 instead of saying that the file is missing. A relative path is resolved against the working directory of the running program, which is often not the directory of the source file (see the [FAQ](https://json.nlohmann.me/home/faq/#parsing-a-file-fails-with-unexpected-end-of-input)).
- **Don't read the file into a string first.** Parsing from a `std::ifstream` is only about 10 to 20 % slower than reading the whole file into a string with one `read()` and parsing that, and it needs no memory for the copy (see [input sources and performance](https://json.nlohmann.me/features/parsing/#input-sources-and-performance)). The common way to read a file with `std::istreambuf_iterator<char>` is so slow that it takes about twice as long as parsing from the stream. Read the file into a string only if you need the text itself, for example for an error message. This advice is for `json::parse`. [`json_document`](https://json.nlohmann.me/features/json_view/index.md) reads a stream into a buffer that it owns anyway, so there is no copy to save: reading the file into a `std::string` yourself and passing that as an lvalue, which the document borrows, was about 6 to 12 % faster than parsing from the stream, with the same single buffer.
- `parse` requires the file to hold exactly one JSON value. Files with one value per line are read with [JSON Lines](https://json.nlohmann.me/features/parsing/json_lines/index.md); files too large for memory are covered in [Large, streamed, and partial input](https://json.nlohmann.me/features/parsing/large_and_partial_input/index.md).
## Writing a JSON file
[`dump`](https://json.nlohmann.me/api/basic_json/dump/index.md) the value into a string first, then write the string:
```
void write_json_file(const std::string& path, const json& j)
{
const std::string text = j.dump(4) + '\n'; // may throw: nothing is written yet
std::ofstream f(path, std::ios::binary);
if (!f.is_open())
{
throw std::runtime_error("cannot open " + path);
}
f << text;
f.close();
if (f.fail())
{
throw std::runtime_error("cannot write " + path);
}
}
```
- **Serialize before opening the file.** Opening a `std::ofstream` truncates the file. `dump` and [`operator<<`](https://json.nlohmann.me/api/operator_ltlt/index.md) throw [`type_error.316`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error316) when a string is not valid UTF-8 (see [handling invalid UTF-8](https://json.nlohmann.me/features/serialization/#handling-invalid-utf-8)), and `f << std::setw(4) << j` may already have written part of the value when it throws. Serializing into a string first leaves the old file untouched in that case.
- **Check the stream after closing it.** A full disk or a missing permission sets the stream's error state; it does not throw unless you enabled exceptions on the stream with `exceptions()`.
- `std::ios::binary` writes the text as it is. Without it, Windows writes `\r\n` for every newline of a pretty-printed value.
## Replacing a file without corrupting it
The library never writes a file itself, so this section is not about the library. It is general C++ advice for a problem users of the library keep running into.
A program that crashes or is killed while it writes leaves a truncated file behind. To make sure readers see either the old or the new contents, write to a temporary file in the same directory and rename it over the original (C++17, `<filesystem>`):
```
#include <filesystem>
void replace_json_file(const std::filesystem::path& path, const json& j)
{
std::filesystem::path tmp = path;
tmp += ".tmp"; // use a unique name if several processes may write the file
write_json_file(tmp.string(), j);
std::filesystem::rename(tmp, path); // replaces path
}
```
The temporary file must be in the same directory (more precisely, on the same file system) as the target: a rename across file systems does not fall back to a copy, it fails and throws `std::filesystem::filesystem_error`. On POSIX systems, the rename atomically replaces the file. Standard C++ has no way to flush a file to the disk (`fsync`), so this protects against a crashed program, but not necessarily against a power loss.
## Binary formats
The [binary formats](https://json.nlohmann.me/features/binary_formats/index.md) work the same way, with the streams opened in binary mode:
```
// read
std::ifstream in("data.cbor", std::ios::binary);
json j = json::from_cbor(in);
// write
const std::vector<std::uint8_t> bytes = json::to_cbor(j);
std::ofstream out("data.cbor", std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
```
Without `std::ios::binary`, Windows turns the bytes `0x0D 0x0A` into `0x0A` and may stop at a byte `0x1A` while reading, and turns `0x0A` into `0x0D 0x0A` while writing, which corrupts the data.
## See also
- [Parsing](https://json.nlohmann.me/features/parsing/index.md) - the inputs `parse` accepts
- [Serialization](https://json.nlohmann.me/features/serialization/index.md) - the options of `dump`
- [`parse`](https://json.nlohmann.me/api/basic_json/parse/index.md), [`dump`](https://json.nlohmann.me/api/basic_json/dump/index.md)
- [`operator>>`](https://json.nlohmann.me/api/operator_gtgt/index.md), [`operator<<`](https://json.nlohmann.me/api/operator_ltlt/index.md)