문제

i want to make C program, "animal.c".
and in shell,
when i type

>animal -cat

the result is "meow"

>animal -dog

the result is "bow".
is it only way?

void main(int argc, char **argv){
if(argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == 'a' && argv[1][3] == 't')
    printf("meow");
if(argv[1][0] == '-' && argv[1][1] == 'd' && argv[1][2] == 'o' && argv[1][3] == 'g')
    printf("bow");
}

in other case, when i want to make file 'cat' which locates in "/animal" ,
assuming that the folder 'animal' already locates in root directory.

     animal -cat  

the result is making file "cat" in "/animal"
the file "cat"'s absolute path is "/animal/cat"

how to do ?
is there another way to receive option value?

도움이 되었습니까?

해결책

getopt is a popular and an almost standard way of parsing command line options. You should use that (or something similar) rather than parsing command line arguments by hand. It's tremendously error prone.

다른 팁

If you pass a filename, you should not put '-' in front of it. Actually '-' is a modifier that tells 'single character option*s* follow', '--' is a modifier that tells 'option with name longer than single character follows'.

The first step to easen your pain would be to use strncmp instead of testing each character of the passed argument.

how to do ?

To answer your last question, you need to use something like mkdir in conjunction with fopen to create the file.

is there another way to receive option value? There is a way to get "option" values by redirecting the input. If you had two lines in your program that had 2 fgets:

char name[10];
char date[9];

fgets(name,10,stdin);
fgets(date,9,stdin);

and in a file called data.txt you had

 Bob
 04/27/11

you can redirect the input to your program like

 myprog < data.txt

and it would be like you input the values yourself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top