tomlplusplus/examples/toml_to_json_transcoder.cpp
Mark Gillard 42af364887 refactored parser
Mainly to simplify a the error handling code (it had gotten a bit verbose), but also to reduce compiled binary sizes.

also:
- moved windows terminal code page stuff in examples to a separate file
2020-04-11 19:43:38 +03:00

64 lines
1.4 KiB
C++

// This file is a part of toml++ and is subject to the the terms of the MIT license.
// Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au>
// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
// SPDX-License-Identifier: MIT
/*
This example demonstrates how to parse TOML from a file and
re-serialize it (print it out) to stdout.
*/
#include <iostream>
#include <fstream>
#include "utf8_console.h"
#define TOML_UNRELEASED_FEATURES 1
#include <toml++/toml.h>
using namespace std::string_view_literals;
int main(int argc, char** argv)
{
init_utf8_console();
// read from a file if a path argument is given
if (argc > 1)
{
auto path = std::string{ argv[1] };
auto file = std::ifstream{ path };
if (!file)
{
std::cerr << "The file '"sv << path << "' could not be opened for reading."sv << std::endl;
return -1;
}
try
{
const auto table = toml::parse(file, std::move(path));
std::cout << toml::json_formatter{ table } << std::endl;
}
catch (const toml::parse_error& err)
{
std::cerr << err << std::endl;
return 1;
}
}
// otherwise read directly from stdin
else
{
try
{
const auto table = toml::parse(std::cin, "stdin"sv);
std::cout << toml::json_formatter{ table } << std::endl;
}
catch (const toml::parse_error& err)
{
std::cerr << err << std::endl;
return 1;
}
}
return 0;
}