I wrote this simple code to understand how the argument system works. I dragged a textfile to the .exe file, and get 2 as output instead of 1 as i expected. Why 2? Is Arg 1 the .exe itself? How can i find out the filenames of the arguments?
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i = 0;
const int max = 100000;
if (argc > 0)
{
cout<< argc <<endl;
}
cin.get(); cin.get();
return 0;
}
And an additional question. Where can i inform on how to access each argument and use the informations. My goal is to open all files passed as arguments to the .exe.
This is not a duplicate question, i asked why 2 is returned when you pass 1 argument. The question in the Link is another...
argv[0]
is normally the name of the program being run, and is counted in argc
. If argc >= 2
, the first of your text-file names should be in argv[1]
. You can simply loop over them...
for (size_t i = 1; i < argc; ++i)
if (std::ifstream infile(argv[i]))
...use infile...
else
std::cerr << "ERROR - unable to open " << argv[i] << '\n';
For more complex requirements, you may want to use getopt()
et al if your system provides it, or the boost library equivalents.