Small explanation needed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>

using namespace std;

int main (int argc, char *argv[])
{
  if (argc != 2)
    cout<<"usage: "<< argv[0] <<" <filename>\n";
  else {
    ifstream the_file (argv[1]);
    if (!the_file.is_open())
      cout<<"Could not open file\n";
    else {
      char x;
      while (the_file.get (x))
        cout<< x;
    }
  }
}



http://www.cplusplus.com/reference/iostream/ifstream/

http://www.cplusplus.com/reference/iostream/fstream/


consider the code above. i understand what the program does and that binary name and file name (the second argument) are passed to the argv[] array. i also understand that argc counts the number of arguments.

but what is "the_file"? where does it come from? where has it been defined? i searched the two links above and i cant find "the_file" anywhere.

also where is argc and argv[] defined? does the compiler just naturally know what those are and what they do?
argv[1] is the first argument passed. So, you need to open this from a command line, with a filename as the first argument. "myProgram /my/file/path/file.txt"
cout<<"usage: "<< argv[0] <<" <filename>\n";


yes, i understand how to use the program and what it does.

but i am trying to understand what are some of the individual elements of the code are, more specifically "the_file". where is "the_file" defined? one cannot just start typing random things into sourcecode because the compiler will complain, right?
Ok, if I understand what you are asking,

"the_file" is a variable name.
for instance:
char x;
x is the variable name, and char is the type.
with:
ifstream the_file;
the_file is the variable name, and ifstream is the variable type.

after you set the value to the variable "ifstream the_file(argv[1])", you then work with the file by using the variable name (in this case "the_file"). "the_file" is not a special keyword, it could easily be "myFile" or "someFile", as long as you the same identifier whenever you are using it.
thank you very much!!!

i just had a small epiphany after i read your post. it makes so much more sense now!! :)

edit: needless to say, i have yet to fully understand <fstream>
Last edited on
Topic archived. No new replies allowed.