Reputation: 597
So the purpose of my program is to simulate a chat- one text file contains responses (call it r.txt) and I write my messages to another (call it m.txt). What I'm looking to do is write code for it in a c file using xcode, then call the program in my command terminal (I'm using Mac OSX). My question is- how does one pass multiple arguments to a C program using the terminal?
I see that in main theres 2 variables, int argc and const char* argv[]. So then does C use the array to account for multiple command line arguments? Cause essentially I'd do something like "$(name of the program), file_name_1, file_name_2." How would I reference these in my C file?
Upvotes: 0
Views: 638
Reputation: 677
The main
function is: int main(int argc, const char *argv[])
.
The first one argc
is the number of elements in the array argv
. The first element argv[0]
is the name of the program. After that you have the strings of each given parameters.
The command line (shell) separated the parameters (by default) with spaces. So myprog foo bar
will result to argv[0]="myprog" argv[1]="foo" argv[2]="bar"
(and here argc=3
).
Several spaces are not taken in count. If you parameters contain spaces you have to use quotes (i.e. myprog "arg with spaces" other "many if wanted"
.
Upvotes: 3