从命令行读取文件名并在Visual Studio中打开
问题描述:
我想打开通过命令行收到的文件名,并对其进行一些更改。从命令行读取文件名并在Visual Studio中打开
我在做视觉工作室。我在我的源代码所在的相同的文件夹中有我的输入文件。 但这不起作用。我究竟做错了什么 。请指出。
这是我的代码。
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;
}
答
为什么不使用绝对路径,那么无论你如何启动程序,它都能正常工作。
#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;
}
此外,你应该把输入和输出文件放在程序的目录中。
如果您指定输入文件的完整路径,您的代码是否工作?运行程序时的当前目录可能与源代码不同。 – 2014-10-10 02:23:03
默认情况下,Visual Studio将您的可执行文件构建在与包含源代码的目录不同的目录中。如果(例如)你传递了一个完整的文件路径,它会(很可能)正常工作。否则,您需要进入VS的调试选项,并在运行时将所需的正确目录设置为当前默认值。 – 2014-10-10 02:24:01
是这个使用? string input =“C:\ CP \ Coding \ codechef problems \ codechef problems \”; input1 = argv [1]; input + = input1; infile.open(input.c_str()); – user3126404 2014-10-10 02:40:35