tags:

views:

423

answers:

3

Hello,

I'm learning C++, then i was searching for some codes for learn something in the area that i love: File I/O, but i want to know how i can tweak my code for the user type the file that he wants to see, like in wget, but with my program like this:

C:\> FileSize test.txt

The code of my program is here:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  long begin,end;
  ifstream myfile ("example.txt");
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}

Thanks!

+1  A: 

Main takes two arguments, which you can use to do this. See this:

Uni ref

MSDN reference (has VC specific commands

Hooked
+3  A: 

main() takes parameters:

int main(int argc, char** argv) {
    ...
    ifstream myfile (argv[1]);
    ...
}

You could also get clever, and loop for each file specified on the command line:

int main(int argc, char** argv) {
    for (int file = 1; file < argc;  file++) {
        ...
        ifstream myfile (argv[file]);
        ...
    }
}

Note that argv[0] is a string pointing to the name of your own program.

lavinio
Minor spelling mistake "args[1]" should be "argv[0]"
Kane Wallmann
Thanks for the help!!!!
Nathan Campos
Ahh yes of course "args" should still be "argv" though
Kane Wallmann
+6  A: 

In the example below argv contains command line arguments as null terminated string array and argc contains an integer telling you how many arguments where passed.

#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
  long begin,end;
  if( argc < 2 )
  {
     cout << "No file was passed. Usage: myprog.exe filetotest.txt";
     return 1;
  }

  ifstream myfile ( argv[1] );
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}
Kane Wallmann
Thanks, for the code!
Nathan Campos
That should be ifstream myfile ( argv[1] );As argv[0] contains the name of the executable file.
Matt H
Woops should be argv[1] not argv[0]
Kane Wallmann
But when i type a file or don't type the message of the program is every: size is: 0 bytes. **Whats worong?**
Nathan Campos
The `argc` check is wrong. `argc==1` is no arguments, `argc>=2` is at least 1 argument.
ephemient
Ahh yes that should be updated as well, I'll edit the post to reflect the corrections.
Kane Wallmann
It's still wrong. You probably mean `if (argc < 2)`, not `if (argc >= 2)`.
ephemient
I fixed it, argc<2 now
KPexEA