命令行选项创建文件的方式
我想制作 C 程序“animal.c”。
在外壳中,
当我输入的
>animal -cat
结果是“喵”,
>animal -dog
结果是“弓”。
这是唯一的方法吗?
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");
}
在其他情况下,当我想制作位于“/animal”中的文件“cat”时,
假设文件夹“animal”已经位于根目录中。
animal -cat
结果是在“/animal”中创建文件“cat”
文件“cat”的绝对路径是“/animal/cat”
怎么办?
还有其他方式获得期权价值吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果传递文件名,则不应在其前面添加“-”。实际上“-”是一个修饰符,告诉“后面是单字符选项*s*”,“--”是一个修饰符,告诉“后面是名称长于单个字符的选项”。
减轻痛苦的第一步是使用 strncmp 而不是测试传递参数的每个字符。
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.
getopt 是一种流行且几乎标准的解析命令行的方法选项。您应该使用它(或类似的东西)而不是手动解析命令行参数。这是非常容易出错的。
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.
怎么办?
要回答你的最后一个问题,你需要使用类似 的内容mkdir 与 fopen 结合创建文件。
还有其他方式接收期权价值吗?
有一种方法可以通过重定向输入来获取“选项”值。如果你的程序中有两行有 2 个 fget:
并且在一个名为 data.txt 的文件中,你
可以将输入重定向到你的程序
,就像你自己输入值一样。
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:
and in a file called data.txt you had
you can redirect the input to your program like
and it would be like you input the values yourself.