I'm trying to read in a file specified in the command line but I'm having some trouble. The command line entry specifies the inputfile preceded by '<' and the output file preceded by '>' like so
int main(int argc,char* argv[])
{
string strv="-v";
string input="<";
string output=">";
string str;
string input_file;
constchar* in=input_file.c_str();
string output_file;
constchar* out=output_file.c_str();
bool verbose=false;
int i;
//deal with command line paramaters
for (i=0;i<argc;i++)
{
cout<<"argc="<<argc<<" and argv at "<<i<<" is "<<argv[i]<<endl;
if (argv[i]==strv)
verbose=true;
elseif (argv[i]==input)
input_file=argv[i+1];
elseif (argv[i]==output)
output_file=argv[i+1];
else // nop
;
}
ifstream fin(in,ifstream::in);
This compiles ok, but when i run it using ./program -v < test1.cmd
I get a segfault, if i cout argc it returns '2' where i would expect for this command line entry, I 'd get 4.
I'm not yet outputting to file, just to the screen so im not specifying an output file yet.
If anyone could help on this it'd be much appreciated.
The value of variable in is an address of an empty character array that (the address) becames invalid after assigning a new value to input_file. You should remove declarations of in and out and use
Thanks for that, however argc is still taking a value of 2 when there should be 4??
I've found now that if i change string input="in"
and pass ./program -v in test1.cmd
to the command line it works fine however the spec for my assignment requires the < before the filename?
I'm using cygwin so im not sure if my issue is specific to that or if < has some special meaning as this and anything beyond it is not being read into argv[].
Symbols < and > has special meaning in the command line. Symbol < means that the standard input stream will be read from a file with the name following <. Symbol > means that standard output stream will be redirected in a file with the name following >. So the command line processor processes this symbol before passing the command line parameters to a calling program.