Skip to content

Commit

Permalink
Add parseFile utility function
Browse files Browse the repository at this point in the history
Since parsing toml from file must be a common use-case, parseFile
would be useful for a casual user.

BUG=#32
  • Loading branch information
mayah committed Nov 6, 2017
1 parent 99b582f commit 8fe8909
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 4 deletions.
14 changes: 14 additions & 0 deletions include/toml/toml.h
Expand Up @@ -9,6 +9,7 @@
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <istream>
#include <sstream>
Expand Down Expand Up @@ -213,6 +214,8 @@ struct ParseResult {

// Parses from std::istream.
ParseResult parse(std::istream&);
// Parses a file.
ParseResult parseFile(const std::string& filename);

// ----------------------------------------------------------------------
// Declarations for Implementations
Expand Down Expand Up @@ -387,6 +390,17 @@ inline ParseResult parse(std::istream& is)
return ParseResult(std::move(v), std::move(parser.errorReason()));
}

inline ParseResult parseFile(const std::string& filename)
{
std::ifstream ifs(filename);
if (!ifs) {
return ParseResult(toml::Value(),
std::string("could not open file: ") + filename);
}

return parse(ifs);
}

inline std::string format(std::stringstream& ss)
{
return ss.str();
Expand Down
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Expand Up @@ -31,6 +31,7 @@ include_directories(../include)

add_executable(parse_stdin parse_stdin.cc)
add_executable(parse_file parse_file.cc)
add_executable(parse_file2 parse_file_2.cc)

function(add_toml_test target)
add_executable(${target}_test ${target}_test.cc)
Expand Down
5 changes: 1 addition & 4 deletions src/parse_file.cc
Expand Up @@ -13,10 +13,7 @@ int main(int argc, char* argv[])
return 1;
}

ifstream ifs(argv[1]);
// Pass ifs without checking error (to test toml::parse detects and error).
// In usual case, I recommend to check ifs state.
toml::ParseResult pr = toml::parse(ifs);
toml::ParseResult pr = toml::parseFile(argv[1]);
if (pr.valid()) {
cout << pr.value;
} else {
Expand Down
25 changes: 25 additions & 0 deletions src/parse_file_2.cc
@@ -0,0 +1,25 @@
#include "toml/toml.h"

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
if (argc < 2) {
cerr << "Usage:" << endl
<< " " << argv[0] << " <input-file>" << endl;
return 1;
}

ifstream ifs(argv[1]);
// Pass ifs without checking error (to test toml::parse detects and error).
// In usual case, I recommend to check ifs state.
toml::ParseResult pr = toml::parse(ifs);
if (pr.valid()) {
cout << pr.value;
} else {
cout << pr.errorReason << endl;
}
}

0 comments on commit 8fe8909

Please sign in to comment.