如何用C来完成通配符功能? [英] how to use C to complete a wildcard function?
问题描述
我是C的菜鸟,现在想用C来完成一个通配符功能.比如我写了一个名为myphoto的照片处理程序,我想这样使用它:myphoto ./photos/*.png,然后myphoto将处理所有目录中的png文件一一.
I am a rookie on C, and now I want to use C to complete a wildcard function. For example, I write a photo processing program named myphoto, and I want to use it like this: myphoto ./photos/*.png, and then myphoto will process all the png file in the dir one by one.
我想尽可能简单地解决这个问题,不使用正则表达式,我想出了一个想法,也许我可以使用 EXEC 函数来执行命令,但是EXEC 函数只返回 int,而不返回 char*.
I would like to solve this problem as easily as possible, without the usage of regular expression, and I came up with a idea that maybe I could use the EXEC function to execute a command, but the EXEC function only returns int, not the char*.
那么我该如何解决这个问题呢?谢谢!
So how can I solve this problem? thanks!
推荐答案
它是特定于操作系统的.我给出了 Posix 和 Linux 的观点(在 Windows 上是不同的,我不知道).
It is operating system specific. I'm giving a Posix and Linux point of view (on Windows it is different, and I don't know it).
注意,如果你正在编写程序 myprog.c
编译成 myprog
然后运行myprog photos/*.png
myprog.c
中的 main
函数正在获取一个字符串数组(声明 int main(int argc, char**argv)
那么参数数组在数组 argv
....) 中有 argc
字符串.扩展由 shell 在启动 myprog
二进制可执行文件之前完成.参见 execve(2)
Notice that if you are writing the program myprog.c
compiled into myprog
then running
myprog photos/*.png
the main
function in myprog.c
is getting an array of strings (declare int main(int argc, char**argv)
then the array of arguments has argc
strings in array argv
....). The expansion is done by the shell before starting your myprog
binary executable. See execve(2)
在 Linux 和 Posix 系统上:阅读 glob(7),你可能想使用 glob(3) 和/或 fnmatch(3) 和/或 wordexp(3).如果某些数据(例如文件中的一行)包含 photos/*.jpeg
并且您的程序想要glob"它,这些函数最有用.您不需要全局化" main
的参数,这已经由您的 shell 完成了.
On Linux and Posix systems: read glob(7), you may want to use glob(3) and/or fnmatch(3) and/or wordexp(3). These functions are useful mostly if some data (e.g. a line in a file) contains photos/*.jpeg
and your program want to "glob" that. You don't need to "glob" the arguments of main
, this has been done already by your shell.
这篇关于如何用C来完成通配符功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!