【问题标题】:C++ command line args (file) not found?找不到 C++ 命令行参数(文件)?
【发布时间】:2014-04-06 21:50:30
【问题描述】:

我有以下主要方法:

int main(string argf)
{

ifstream exprFile(argf);
string inExpr;
if (exprFile.is_open())
{
while ( getline(exprFile,inExpr) )
{
    //do stuff
}
exprFile.close();
}
else cout << "Unable to open file"; 

system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}

我已使用以下命令从命令行运行此程序:

  • "C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
  • C:\Complete Filepath\Project2.exe C:\Differnt Filepath\args.txt
  • "C:\完整文件路径\Project2.exe" "args.txt"
  • C:\完整文件路径\Project2.exe args.txt

最后两个 args.txt 与可执行文件位于同一目录中。所有四个都给出了“无法打开文件”的结果。在对其进行任何操作之前尝试打印 argf 值根本没有产生任何结果。完全空白的打印语句。

然后我进入 Visual Studio 2010 选项,并在参数部分下添加了 args.txt 文件的所有变体,该文件也位于不同的位置,但没有任何效果。

我做错了什么?

您应该如何打开在命令行中作为参数传递的文件?

【问题讨论】:

标签: c++ file command-line arguments


【解决方案1】:

是的,代码!

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char* argv[])
{
   ifstream exprFile;
   string inExpr;
   for( int i = 1; i < argc; i++) {  // 0 is the program name
      exprFile.open(argv[i]);
      if (exprFile.is_open()) {
         while ( getline(exprFile,inExpr) ) {
            cout << "Doing stuff on line: " << inExpr << "\n";
         }
         exprFile.close();
      }
      else cout << "Unable to open file " << argv[i];
   }
}

【讨论】:

    【解决方案2】:
    int main ( int argc, char *argv[] )
    

    这是从main 获取参数的正确方法。

    argc 是参数的数量。 argv 是参数列表。

    实际参数将以index = 1. 开头index 0 处的值将始终是程序名称。

    在你的例子中,

    "C:\完整文件路径\Project2.exe" "C:\不同文件路径\args.txt"

    argc = 2
    argv[0] = "Project2.exe" 
    argv[1] = "C:\Differnt Filepath\args.txt"
    

    【讨论】:

    • 在这种情况下int argc 是什么?整数有什么用?我假设argv[] 是字符数组(字符串)文件位置?
    • argc 是参数个数; argv 是一个指向指针数组的指针,每个指针都指向一个普通的旧字符数组空终止字符串。 argv[argc] == 0 因此您还可以通过查看指针来检测参数的结尾。
    • 谢谢你们。我想我找错地方了。我认为我的问题是命令行调用过程而不是参数传递。我看到这在其他地方也得到了很好的介绍。
    • @JonathanLeffler 感谢您提供有关 argv[argc] ==0 检查的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多