PDA

View Full Version : C++: Arbitrary File Input


Karim
03-11-2005, 05:53 PM
I can open a file when the filename is hard coded or if I ask the user and store the filename into a string. But I have no idea how to open a file when the filename is only specified at run-time on the command line. For instance:

myProg filename1
myProg filename2
etc.,

myProg needs to input the text from the various files for processing but I don't know how to get at the contents. This isn't redirection either which I would be fine with.

Any ideas?

CraigSca
03-11-2005, 05:56 PM
It's been years since I programmed in C, but isn't this part of the main function? Like, argv() and argc()?

gstelmack
03-11-2005, 06:17 PM
Yup, you need to use the argc and argv parameters to main. argc is the parameter count, and argv is an array of strings that are the command-line parameters tokenized by whitespace.

Karim
03-11-2005, 07:59 PM
Thanks... something I hadn't seen before.

MikeVic
03-11-2005, 08:26 PM
I believe array slot 2 has the first command line specified? The first one is the name of the program or something?

gstelmack
03-11-2005, 09:15 PM
Well, technically it's array slot 1, since C/C++/C# use zero-based indexing ;-)

So if argc == 1, there are no arguments, just the name of the program in argv[0].