How do you use int main(int argc, char* argv[])

So, I have an idea of how to use int main(int argc, char* argv[]) but I don't know how to use it in the command line.

What I want to do is to copy a set of characters from the a file on my desktop, into a array, to then print it on the screen. Can anyone give me some pointers as to what I can do in the command line?
On the command line call
yourprogram yourfile

Some IDEs allow to pass command line arguments to your program without to type them every time if you are still working on it
If you want to be a really cool guy you can also drag the yourfile.txt and drop it on yourprogram.exe

(Its easier if youre working with alot of files)
Last edited on
Ok so maybe I'm confusing myself here. Lets say I created a file named test.txt with the following text:


And this is the code I run:
#include <iostream> 
using namespace std;

int main(int argc, char* argv[]) { 
   cout << "argc = " << argc << endl; 
   for(int i = 0; i < argc; i++) 
      cout << "argv[" << i << "] = " << argv[i] << endl; 
   return 0; 

when I type /test.out test.txt it outputs:
argc = 2
argv[0] = /test.out
argv[1] = test.txt
argv[2] = Segmentation fault (core dumped)

What do I need to do to make what's in the test.txt file from above?

Last edited on
Well, argc holds the amount of arguments passed to the "console" (including the .exe call) and argv contains char*'s that are seen as strings (which you can refer to up to argc-1). When you check argv[1] for a file name, you can use that as the input for the creation of a filestream to that file. Check the tutorial section on file streams and you'll know what I mean.
Ok so I see how it works. But... still my question is.... how can I use this to output what is inside the file?
Thanks for the reply all. I found what I was looking for
Topic archived. No new replies allowed.