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;
    }
}

}

Ðаn
  • 10,934
  • 11
  • 59
  • 95
PING_LORD
  • 11
  • 4
  • Don't forget about things like [`getopt`](https://man7.org/linux/man-pages/man3/getopt.3.html) to make argument parsing easier and more reliable. This code will crash, hard, if `argc` isn't at least 3. – tadman Dec 19 '20 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". – Hans Passant Dec 19 '20 at 13:40

1 Answers1

-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

Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32