How to read "string" from command line argument in 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 r开发者_如何学Cun my code './myprogram hello' compared to './myprogram alongerinput'
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]);
Here is example that converts command line arguments to single string:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 1)
return 0;
int i;
int strsize = 0;
for (i=1; i<argc; i++) {
strsize += strlen(argv[i]);
if (argc > i+1)
strsize++;
}
printf("strsize: %d\n", strsize);
char *cmdstring;
cmdstring = malloc(strsize);
cmdstring[0] = '\0';
for (i=1; i<argc; i++) {
strcat(cmdstring, argv[i]);
if (argc > i+1)
strcat(cmdstring, " ");
}
printf("cmdstring: %s\n", cmdstring);
return 0;
}
argv
is a pointer to an array of null-terminated strings. You do not need to know the size of the string; all you need to do is point to the value since the end of the string is indicated with a '\0'.
char* init_d = argv[0];
printf("%s", init_d);
If you did want to know the length of the string you could use strlen(argv[0])
.
int main(int argc, char **argv){
while(--argc>0)
printf("%s\n",*++argv);
return 0;
}
argc: argument count i.e. number of arguments in command line
argv: argument vector
if your program is myProg
then myProg hello
in command line has argc=2 (including program name), argv[0] is "myProg", and argv[1] is "hello"
After running
init_d = *(argv++);
(parens not necessary, btw), init_d is a pointer to a character. In C, a string is a character pointer that adheres to the contract that if it is advanced far enough, eventually a null character ('\0') will be reached, signifying the end of the string. In other words, init_d is now precisely the string you want. You can print it with
printf("%s", init_d);
Note, btw, that *argv++ is giving you the first element of argv, which is actually the name of the function on the command line. You probably want the first command line argument, which you'll get with *++argv.
You can output the string you pointing with init_d at with
printf("%s", init_d);
"%s" output all characters of the string until it reach a '\0'. In C, strings are null terminated.
精彩评论