Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File input without specified file name?

Status
Not open for further replies.

Puritan2

Technical User
Jul 23, 2003
8
CA
If the user is going to run my executable but specifies differing filenames each time it is run:

e.g., MyProg file1
e.g., MyProg file2

where file1, file2 are text files, how do I handle this? I can handle it using .open("filename") but I'm not sure how to do it otherwise...

Thanks-you.
 
Code:
int main ( int argc, char *argv[] ) {
    // check argc to see how many parameters were specified
    // first parameter is argv[1]
    // so perhaps
    open( argv[1] );
}

--
 
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

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

//This worked.  Thanks!
 
You want to error check to make sure the correct number of arguments are passed, else the program will exit horribly if not passed a parameter.

In general argv is a array of char pointers or a char double pointer (both are the same as far as the machine code is concerned). argv[0] is the program name, argc is the size of argv (so, no parameters should argc == 1, with program name at an index of 0; with one parameter argc == 2, with argument index at 1... and so on).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top