1

I am writing a program that uses Boost's Program Options library, I am not able to validate file extension using boost::program option:

 po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("diff,d", po::value< std::string >(),"Specify the .xyz file, name of the .xyz to create")**.xyz file I want to validate,while givin input as comman line **
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, desc), vm);
    po::notify(vm);
Arif_Khan
  • 31
  • 4

1 Answers1

1

Ok, you need to implement validate

You can use a tag type so you can associate your validate by Argument Dependent Lookup:

Live On Coliru

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <iostream>

namespace tag {
    struct xyz_file {};

    bool validate(boost::any& v, std::vector<std::string> const& ss, xyz_file*, int) {
        if (ss.size() == 1 && boost::algorithm::iends_with(ss.front(), ".xyz"))
        {
            v = ss.front();
            return true;
        }
        return false;
    }
}

namespace po = boost::program_options;

int main(int ac, char** av) {
    po::options_description desc("Allowed options");
    desc.add_options()
        ("diff,d", po::value<tag::xyz_file>(), "xyz files only")
        ;

    po::variables_map vm;

    po::store(po::parse_command_line(ac, av, desc), vm);
    po::notify(vm);

    if (!vm["diff"].empty())
        std::cout << "Parsed: " << vm["diff"].as<std::string>() << "\n";
    else
        std::cout << desc;
}
sehe
  • 374,641
  • 47
  • 450
  • 633