How to give File name as a command line argument in CLion

Viewed 748

I need to read a file from the command line argument and then do some operations on its contents. I have written a small code to test it.

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

int main(int argc, char* argv[]) {
    using std::cout;
    using std::endl;
    using std::string;

    if (argc != 2) {
        cout << "Usage: ./a.out Filename"
             << endl;
        return 1;
    }
    std::fstream input(argv[1], std::ios_base::in);
    string word;
    while(getline(input, word)) {
        cout << word;
    }
    return 0;
}

This code works fine if I run it in the terminal by ./a.out filename.txt

I am writing code in CLion so I need to give the filename/file-path in CLion as a command-line argument.

I tried adding the filename as an argument in Run -> Edit Configurations -> Program arguments but as far as I understand CLion is treating the filename.txt as a simple argument, not a filename. I also tried giving the path to the file but with no luck, CLion still does not read the file contents when I hit run.

0 Answers
Related