[try Beta version]
Not logged in

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

Sep 3, 2010 at 3:04pm
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?
Sep 3, 2010 at 3:09pm
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
Sep 3, 2010 at 3:14pm
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 Sep 3, 2010 at 3:14pm
Sep 3, 2010 at 7:47pm
Ok so maybe I'm confusing myself here. Lets say I created a file named test.txt with the following text:

ABCD
1234

And this is the code I run:
1
2
3
4
5
6
7
8
9
#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 Sep 3, 2010 at 7:48pm
Sep 3, 2010 at 7:51pm
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.
Sep 3, 2010 at 8:30pm
Ok so I see how it works. But... still my question is.... how can I use this to output what is inside the file?
Sep 3, 2010 at 8:46pm
Thanks for the reply all. I found what I was looking for http://www.cprogramming.com/tutorial/lesson14.html
Topic archived. No new replies allowed.