How to read a file name argument from the command line in C++

Reading a file name parameter from the command line is a common task. In this post I read a file name and validate it exists. For paths and file names that include spaces, you have to pass them between quotes, otherwise they will be interpreted by the operating system as two different parameters.

#include <string>
#include <iostream>
#include <fstream>

int main(int argc, char* argv[]) {
    for (int i = 1; i < argc; i++) {
        std::string s(argv[i]);
        if (s.rfind("--input=", 0) == 0) {
            std::ifstream f(s.substr(std::string("--input=").length()));
            if (f.good()) std::cout << "File exists" << std::endl;
            else std::cout << "File not found" << std::endl;
        } else {
            std::cout << "Unknown: " << s << std::endl;
        }
    }
    return 0;
}

Leave a Reply