Shell重定向与显式文件处理代码
我不是母语为英语的人,所以请原谅这个问题的尴尬标题。 我只是不知道如何更好地表达它。
我在一个FreeBSD盒子里,我有一个用C
编写的小过滤工具,它通过stdin
读取数据列表,并通过stdout
输出一个处理过的列表。 我有点像这样调用它: find . -type f | myfilter > /tmp/processed.txt
find . -type f | myfilter > /tmp/processed.txt
find . -type f | myfilter > /tmp/processed.txt
。
现在我想给我的滤镜更多曝光并发布它。 公约说工具应该允许这样的东西: find . -type f | myfilter -f - -o /tmp/processed.text
find . -type f | myfilter -f - -o /tmp/processed.text
这将迫使我编写简单不需要的代码,因为shell可以完成这项工作,因此我倾向于将其排除在外。
我的问题是:我是否会错过一些参数(除了惯例之外)为什么文件的读写应该在我的代码中完成而不是委托给shell重定向?
这绝对没有错。 您的filter将具有类似于c++filt
的界面。
如果要根据输入文件的名称自动选择输出文件,或者想要在单个命令中处理多个文件的特殊处理,则可以考虑文件处理。
如果您不想做其中任何一个,那么成为一个简单的filter没有任何问题。 任何人都可以提供一组简单的shell包装器,以便在需要时提供cmd infile outfile
语法。
这是一个不必要的限制界面。 从命令行接受参数更灵活,
grep foo file | myfilter > /tmp/processed.text
并不排除使用它
find . -type f -exec myfilter {} + > /tmp/processed.text
实际上,与shell重定向具有相同的效果,您可以这样做:
freopen( "filename" , "wb" , stdout );
因此,如果您在整个代码中使用了printf,输出将被重定向到文件。 因此,您无需修改之前编写的任何代码,并且可以轻松地适应约定。
使用filename参数运行任何命令都很好。 如在你的例子中:
myfilter [-f ./infile] [-o ./outfile] #or myfilter [-o outfile] [filename] #and (the best one) myfilter [-f file] [-o file] #so, when the input and output are the same file - the filter should working correctly anyway
对于好的示例,请检查sort
命令。 通常在管道中用作文件管理器,但可以执行[-o output]
并正确处理same input/output problem
…
为什么它好? 例如,当想要通过“fork / exec”从“C”运行命令并且不想启动shell来处理I / O. 在这种情况下,更容易(和更快) execve(.....)
带参数作为使用shell包装器启动cmd。