我有一个程序可以创建文件并使用ofstream写入文件。我需要程序能够稍后解析命令行参数。但是由于某种原因,即使我的程序根本不包含任何命令行参数,当我将文件拖放到编译的可执行文件上时,它也不会创建文件。如果可执行文件正常运行,则可以运行。所以我完全感到困惑。来源如下:

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
    ofstream outfile;
    outfile.open("test.txt");

    if(outfile.is_open())
    {
        outfile << "Test";
        outfile.close();
    }
    else cout << "Unable to open file";

    return 0;
}

有人有什么想法吗?感谢您的帮助。

最佳答案

您根本没有使用命令行参数。重新编码main()方法,如下所示:

int main(int argc, char** argv)
{
  if (argc != 2)
  {
    cout << "Usage: blah.exe file" << endl;
    return 1;
  }
  ofstream outfile;
  outfile.open(argv[1]);
  if(outfile.is_open())
  {
    outfile << "Test";
    outfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

请小心删除,代码会重写文件内容。

关于c++ - Windows控制台应用程序的拖放问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2129043/

10-13 06:30