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?

3
  • 2
    see stackoverflow.com/questions/3024197/… Commented Oct 15, 2015 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. Commented Oct 15, 2015 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? Commented Oct 15, 2015 at 20:14

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.