-2

In C-linux - how can I get an input of unknown number of file names separated by space and save each file name separately as a string? and another question - a friend told me about "args" as a solution for some problems with unknown number of something. so my question is - what is this "args" he talk about??

Thank you very much!

dvir naim
  • 13
  • 2
  • 1
    Do you know `main()`'s signature in c? And you should take care of white spaces embeded in the file names, have you thought about that? – Iharob Al Asimi Jan 20 '15 at 13:18
  • 1
    Please read [How to ask](http://stackoverflow.com/help/how-to-ask). – segarci Jan 20 '15 at 13:19
  • 1
    You'll find anything you need in this [awesome link](https://support.google.com/websearch/answer/134479?hl=en) – nouney Jan 20 '15 at 13:20

2 Answers2

0

Your program will (or should) have a main function like this:

int
main (int argc, char **argv)
{
   ...
}

argc tells you how many arguments your program is passed, and argv is an array of them. IE the arguments are in argv[0] ... argv[argc-1].

Beware that argv[0] is actually the name of the program, rather than the first additional supplied argument, which is in argv[1].

abligh
  • 24,573
  • 4
  • 47
  • 84
0

In c the main() function can take two parameters the first one being the number of arguments and the second an array with the arguments, so you wont need to store each string anywhere you can use this array for the lifetime of the program.

Here is an example of you to print these arguements to the standard output

int main(int argc, char **argv)
{
    int index;
    for (index = 1 ; index < argc ; ++index)
        printf("Argument %d -> %s\n", index, argv[index]);
    return 0;
}

as you can see, the number of arguments is argc, the first argument if the program was invoked from the shell will be the program name, the next arguments are the arguments passed to the program.

Suppose you complied the program like this

gcc -Wall -Wextra -Werror -O0 -g3 source.c -o program

then you can invoke the program this way

./program FileName1 "A file name with spaces embeded" another_file

the output would be

Argument 1 -> FileName1
Argument 2 -> A file name with spaces embeded
Argument 3 -> another_file

usually argv[0] is the program name, but you can't guarantee that, if the program is invoked from a shell, it's pretty safe to assume that though.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97