Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read "string" from command line argument in C?

Tags:

c

I've a question about passing in parameters via the command line.

My main() looks like

int main(int argc, char **argv){
  int b, d, n, flag;  
  char *init_d, tst_dir[100];

  argv++;
  init_d=*(argv++);
  //printf(); <--------What do I have to do to init_d so that I can print it later?

If argv is a pointer to an array of pointers I'm assigning init_d to point to the value being pointed to by the pointer argv points to? (If that even makes sense)

I assume I have to get that value into a character array in order to print it out but if I don't know the size of the "string" I am passing in, I am not sure how to achieve this. For instance if i run my code './myprogram hello' compared to './myprogram alongerinput'

like image 595
mike Avatar asked Feb 18 '11 20:02

mike


1 Answers

You can print the arguments without transferring them into character arrays. They are null-terminated C strings and printf eats them for breakfast:

for (i=0; i<argc; i++)
  printf("%s\n", argv[i]);  
like image 190
David Heffernan Avatar answered Sep 19 '22 02:09

David Heffernan