0

Im making college project to code and decode files. I want it to run from command line something like this:

myapp file_name -code

myapp file_name -decode

How do I get path to file in directory where I opened CMD and how do I save file to same directory? My code if its needed:

int main(int argc, char *argv[]) {
    std::cout << argv[1] << std::endl;
if (argv[2] == "code" || argv[2] == "c") {
    try {
        WriteAllBytes("coded.gau", StringToCharVector(Code(CharVectorToString(ReadAllBytes(argv[1])))));
    } catch (...) {
        std::cout << "Exception!" << std::endl;
    }
} else if (argv[2] == "decode" || argv[2] == "d") {
    try {
        WriteAllBytes("coded.gau", StringToCharVector(Decode(CharVectorToString(ReadAllBytes(argv[1])))));
    } catch (...) {
        std::cout << "Exception!" << std::endl;
    }
}

}

2
  • Don't forget about things like getopt to make argument parsing easier and more reliable. This code will crash, hard, if argc isn't at least 3. Commented Dec 19, 2020 at 11:24
  • The argv[2] checking is wrong, it is not obvious why you can't debug this. In VS use Project > Properties > Debugging > "Command Arguments". Commented Dec 19, 2020 at 13:40

1 Answer 1

-1

You can use

// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;

po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);    
while ((c = getopt (argc, argv, "abc:")) != -1)
    switch (c)
      {
      case 'a':
        aflag = 1;
        break;
      case 'b':
        bflag = 1;
        break;
...

See rest of the example: https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html

QCommandLineParser parser;
parser.setApplicationDescription("Test helper");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));

Rest of the example: https://doc.qt.io/qt-5/qcommandlineparser.html#details

Sign up to request clarification or add additional context in comments.

4 Comments

Is there no way to do this without libraries?
You can parse it your self, What is your mean by without libraries ? your program already linked to libc which you could use getopt().
I thought getopt() is only for Linux
If you follow the rule of asking a good question we guide you better than you ask your question chunk by chunk, See this: stackoverflow.com/a/10404524/9248466

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.