Is there any way to accept all the parameters as a single string?

922 Views Asked by At

For example,

Input:

echo( hello world

Program:

#include<stdio.h>

int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}

Output:

hello world

Now I need hello world in a pointer.

I know that **char doesn't work the way I want it to..

But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?

Some access specifier for char** maybe?

I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.

Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?

3

There are 3 best solutions below

0
Stephan On BEST ANSWER

To echo an empty line, in Windows cmd, the best method is echo(, but also common are echo/, echo. and some more variations.

The (best for cmd) echo( doesn't work in DOS (results in a bad command or filename error), but echo/ works fine even in DOS.

4
ryyker On

I want a way to get all the arguments in a single pointer, a string that's terminated at the end.

Using either form of the main() function:

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

which are equivalent signatures for the C main() function, will allow you to pass any number of arguments, each of any size. If you want to pass a single string containing many arguments just pass a single string with some kind of delimiter. If the delimiter is a space ( " " ), then by definition of the behavior of the C main() function command line argument requires surrounding them with ":

Say your exe name is prog.exe

prog this,is,one,argument
prog "this is one argument"  //double quotes provide cohesion between space delimited command line arguments 
prog this-is-one-argument

Will all be contained in a single variable: argv[1]

If you compile this as echo.exe it will put to stdout any thing typed into stdin:

int main(int argc, char **argv)
{
  if(argv != 2) return 0;
  fputs(argv[1], stdout);
  return(0);
}

Usage: echo "this will be echoed onto stdout"<return>
Usage: abc000<return>
Usage: this-is-one-argument<return>

1
0___________ On

Make it one line.

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

int main(int argc, char **argv)
{
    char oneline[256] = "";
    for(int index = 1; index < argc; index++) 
    {
        strcat(oneline, argv[index]);
        strcat(oneline, " ");
    }

    printf("parameters: "%s"\n", oneline);
}

https://godbolt.org/z/B4ULLB

This is only the idea and it can be done much more efficiently - for example by not using strcat or more efficiently allocate the memory. But the idea will be the same. You can also do not add the last space (it is for nitpickers)