Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ editing the elements of char* argv[]

Tags:

c++

c

linux

All of you know this function:

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

}

I want to write a command line interface in Linux for my program, which is usually done by getopt_long()

My program would be executed from command line like this:

pop3 get --limit 25 --recent 

Hence, the argv[] would include pop3 as its program name, and the rest are treated as options. I want to delete pop3 from my string and set the first token after it as the first element of the array. Is there a way to do that other than looping through?

like image 289
Mostafa Talebi Avatar asked Sep 02 '15 13:09

Mostafa Talebi


1 Answers

Increment the argv pointer, and decrement the argc. Example:

int main(int argc, char *argv[])
{
    argc--;
    argv++;

    return 0;
}

This works, because when you increment argv, you still have the previous data in memory, it's just that the base address of the argv has increased. And you decrement argc, because you now have one less argument.

like image 109
Edward Karak Avatar answered Sep 27 '22 22:09

Edward Karak