0

A little context for my project: We have an arbitrary number of files that need a separate process for each file then need to search using an exec() call to find every time a specific KEY is used. I know how to use grep from the command line using this command:

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

But I cannot figure out how to do this in c++. I found a thread on here that gave me this line.

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

It compiles and runs so I think it works but the problem is I need to output the number of times the pattern occurred to a file and I tried the line below but expectedly it didn't work. It gave this error "grep: out.txt: No such file or directory"

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

Here are the directions of this part of my project.

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 ... ).

Some guidance here would be much appreciated!

arved
  • 4,401
  • 4
  • 30
  • 53
Alex
  • 9
  • 4
  • 1
    http://stackoverflow.com/questions/20488574/output-redirection-using-fork-and-execl – A.S.H Oct 06 '15 at 10:40
  • You are listing your output file as an input file. What you wany is to redirect grep's output. You need to read the link above to see how to do it – A.S.H Oct 06 '15 at 10:45
  • So your project *specifically mentions* that you *don't* execute `grep` directly. And what do you do? You execute `grep` directly. And when it doesn't work, still instead of reading your project's directions, you ask here. Please read your project's directions. –  Oct 06 '15 at 12:07
  • Thanks A.S.H. hvd you are not helpful whatsoever. – Alex Oct 06 '15 at 14:36

1 Answers1

0

For the actual execution as you would do on command line would be:

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

This will mean that the shell would take the line grep -o KEY FILENAME.txt | wc -l > OUTPUT.txt, interpret it and run it. Note that this will include wild card expansion and all what the shell does.

Then of course if you wan't to continue after it has completed you will have to fork first because execl does not return if it's successful at starting the program (ie bash).

skyking
  • 13,817
  • 1
  • 35
  • 57