Accepting command-line arguments

I started doing command line arguments lesson at cprogramming.com/lesson14

And i understand what lesson want to say. But when i enter filename no text appears on screen from it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <fstream>
#include <iostream>

using namespace std;

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] <<" Readme.txt\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
  }
  cin.get();
}


do you know how you must send argument to main function and do it correctly ?
You confused me.. Can u make example for me?
Hi happykiller,

as far as I can tell your program works fine, although I would remove the cin.get() at the bottom and replace it with a return 0. I guess you have this here because you don't want the console to close?

Here is my solution:

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

using namespace std;

int main(int argc, char* argv[])
{
  if(argc != 2)
    cout << "Usage: " << argv[0] << " path/to/file.txt" << endl;

  ifstream the_file(argv[1]);
  if (!the_file)
    cout << "Could not open file\n";

  char x;
  while(the_file.get(x))
    cout << x;

  return 0;
}


Here is an example of its use. Typing at the command line:

./test textfile.txt 


gives the following output:

this is the 
contents of a test
input file.


Also if you try to run with !=2 arguments at the command line:

./test


you get

Usage: ./test path/to/file.txt
Could not open file


Hope this helps.
yes and tnx @dangrr888 . this is a true code and send arg to main function. you must run your exe in cmd-command line- and send your arg in this

C:\mypro.exe mytxt.txt
Topic archived. No new replies allowed.