Shivi Bar lev
Shivi Bar lev

Reputation: 13

Is there a way to limit the number of command line arguments?

I am trying to do an implementation of the command 'echo' in C.

I would like to have the entire sentence after the command 'echo' read into argv[1] in the command line instead of having each word passed as a separate argument.

Is that possible in C?

Upvotes: 0

Views: 976

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50831

You can't do this directly, because the shell is splitting the arguments even before your program starts.

Maybe you want something like this:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char sentence[500] = { 0 };

  for (int i = 1; i < argc; i++)
  {
    strcat(sentence, argv[i]);
    if (i < argc - 1)
      strcat(sentence, " ");
  }

  printf("sentence = \"%s\"", sentence);
}

Disclaimer: no bounds checking is done for brevity.

Example of invoking:

> myecho Hello World 1 2 3
sentence = "Hello World 1 2 3"

Upvotes: 1

cocool97
cocool97

Reputation: 1251

You can rather loop over every element of argv by using argc to ensure you you won't read too deep.
You can also you require the launch of your programm to be : ./myProgram "Here is my nice sentence"

Upvotes: 1

Related Questions