gpt4 book ai didi

c++ - 将 grep 与 execl() 一起使用

转载 作者:行者123 更新时间:2023-11-30 17:10:12 28 4
gpt4 key购买 nike

我的项目的一些背景信息:我们有任意数量的文件,每个文件需要一个单独的进程,然后需要使用 exec() 调用进行搜索,以在每次使用特定 KEY 时进行查找。我知道如何使用以下命令从命令行使用 grep:

grep -o KEY FILENAME.txt | wc -l > OUTPUT.txt

但是我不知道如何在 C++ 中做到这一点。我在这里找到了一个线程给了我这条线。

execl("/bin/grep","grep",pattern,filename,NULL);

它编译并运行,所以我认为它可以工作,但问题是我需要输出该模式在文件中出现的次数,我尝试了下面的行,但预计它不起作用。它给出了这个错误“grep:out.txt:没有这样的文件或目录”

execl("/bin/grep", "grep",pattern,fileName,output,NULL);

这是我的项目这一部分的方向。

You can do this by means of the system call exec() , providing it with the path to the executable of the shell (typically, /bin/sh ) and, as arguments of /bin/sh , the string -c and the string corresponding to the search command ( grep -o ... ).

这里的一些指导将不胜感激!

最佳答案

对于实际执行,就像在命令行上执行的那样:

 execl("/bin/sh", "/bin/sh", "-c", "grep -o KEY FILENAME.txt | wc -l > OUTPUT.txt")

这意味着 shell 将采用行 grep -o KEY FILENAME.txt | wc -l > OUTPUT.txt,解释它并运行它。请注意,这将包括通配符扩展以及 shell 执行的所有操作。

当然,如果您不想在完成后继续,则必须首先fork,因为如果execl成功启动程序,则不会返回(即bash)。

关于c++ - 将 grep 与 execl() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967706/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com