简体   繁体   English

如果从环境变量运行,如何将文件路径作为参数传递给程序? C++

[英]How to pass file path to program as argument if it runs from environment variable? C++

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 文件名-代码

myapp file_name -decode myapp 文件名 -decode

How do I get path to file in directory where I opened CMD and how do I save file to same directory?如何在打开 CMD 的目录中获取文件路径以及如何将文件保存到同一目录? 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;
    }
}

} }

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参见示例的 rest: https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.ZFC35FDC70D5FC69D2693EZ75A

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 Rest 示例: https://doc.qt.io/qt-5/qcommandlineparser.html#details

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM