0

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?

David Tamrazov
  • 567
  • 1
  • 5
  • 16
  • 2
    see http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean – Les Oct 15 '15 at 20:10
  • Each element of the array `argv` (read as: "argument values") at index `1` or greater is a C string containing one of the command-line arguments (`argv[0]` conventionally contains the name of the program). The `argc` (read as: "argument count") tells you how many of those there are. – John Bollinger Oct 15 '15 at 20:12
  • Okay I get you.. so then if I do something like "$(name of the program"), r.txt, m.txt", then argv[1] would be r.txt and argv[2] would be m.txt? – David Tamrazov Oct 15 '15 at 20:14

1 Answers1

3

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".

hexasoft
  • 677
  • 3
  • 9