- Code: Select all
int main ( int argc, char *argv[] )
What does that allow you to do? Does it allow you to code from the terminal or cmd? I'm just not understanding what fully declaring main does, i would greatly appreciate a explanation.
int main ( int argc, char *argv[] )
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) // argc should be 2 for correct execution
// We print argv[0] assuming it is the program name
cout<<"usage: "<< argv[0] <<" <filename>\n";
else {
// We assume argv[1] is a filename to open
ifstream the_file ( argv[1] );
// Always check to see if file opening succeeded
if ( !the_file.is_open() )
cout<<"Could not open file\n";
else {
char x;
// the_file.get ( x ) returns false if the end of the file
// is reached or an error occurs
while ( the_file.get ( x ) )
cout<< x;
}
// the_file is closed implicitly here
}
}
WallShadow wrote:The arguements to the main function help pass additional information to the program. The int passed is the number of arguments you have, and the char * [] is an array of pointers to null-terminated strings.<br><br>What is this for? It basically helps give a program immediate information about the way that it should work. for example;<br><br>to start notepad with a blank file, you just start it with the command line "notepad.exe", but if you want to immediately open a txt file with notepad, you use the command line "notepad.exe C:/blah/mytxtfile.txt" that 'C:/blah/mytxtfile.txt' will be stored in the second argument to the program ( the first arguement is always the program's name ). Many command line utilities also use command line arguements. such as starting command prompt with "cmd.exe" or "cmd.exe /k dir" will produce different results.
Users browsing this forum: No registered users and 0 guests