【问题标题】:Reading a filename from commandline and opening in visual studio从命令行读取文件名并在 Visual Studio 中打开
【发布时间】:2014-10-10 02:19:03
【问题描述】:

我想打开通过命令行接收到的文件名并对其进行一些更改。

我在视觉工作室做。我的输入文件在我的源代码所在的文件夹 中。 但这不起作用。我究竟做错了什么 。请指出来。

这是我的代码。

 using namespace std;   
  int main(int argc, char** argv)
  {
    ifstream infile;
    ofstream outfile;
    string input="";
    string output="";
    if( argc == 3 ) {
    input = argv[1];
    output = argv[2];
  cout<"arguments right!";
}
else {
  cout << "wrong entry format. Parameters not correct";
  return 1;
}

infile.open(input.c_str());
if (infile.fail()) 
    cout<<"Could not open file.";
else
    cout<<"File opened perfect ";
return 0;
}

【问题讨论】:

  • 如果您指定输入文件的完整路径,您的代码是否有效?运行程序时的当前目录可能与源所在的目录不同。
  • 默认情况下,Visual Studio 在与包含源代码的目录不同的目录中构建您的可执行文件。如果(例如)您将完整路径传递给文件,它(很可能)会正常工作。否则,您需要进入 VS 的调试选项,并在运行时将所需的正确目录设置为当前默认目录。
  • 这个可以用吗? string input="C:\CP\Coding\codechef 问题\codechef 问题\";输入1=argv[1];输入+=输入1; infile.open(input.c_str());
  • 这是我的完整路径
  • 请记住,字符串文字中的反斜杠需要转义或只使用正斜杠。尽管 Visual Studio 应该对此提出警告。

标签: c++ visual-studio-2010 file filestream iostream


【解决方案1】:

为什么不使用绝对路径。那么无论你如何启动程序,它都可以正常工作。

#include <fstream>
#include <string>
#include <iostream>
using namespace std;   
int main(int argc, char** argv)
{
    ifstream infile;
    ofstream outfile;
    string input = "";
    string output = "";
    string work_dir = argv[0];
    //get the directory of program.
    work_dir = work_dir.substr(0, work_dir.rfind('\\') + 1);
    if( argc == 3 ) 
    {
        input = work_dir + argv[1];
        output = work_dir + argv[2];
        cout << "arguments right!";
    }
    else 
    {
        cout << "wrong entry format. Parameters not correct";
        return 1;
    }
    infile.open(input.c_str());
    if (infile.fail()) 
        cout<<"Could not open file.";
    else
        cout<<"File opened perfect ";
    return 0;
}

另外,你应该把输入和输出文件放在程序的目录下。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 2021-05-04
    • 2015-07-10
    • 2021-12-07
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多