I'm trying to work through a simple hackerank problem and I'm stuck. When executing grep on the command line, I have no issues
grep -i \"the[^a-z0-9]\" $filename <<< "from fairest creatures we desire increase"
result: (returns nothing)
grep -i \"the[^a-z0-9]\" $filename <<< "the clock struck twice"
result: the(highlighted) clock struck twice
I read this article :
Can I open bash from a popen() stream?
I have tried prepending the grep command with "exec bash -c" and "/bin/bash -c" to no avail.
Can anyone tell me why I'm getting this error and how to fix it?
sh: 1: Syntax error: redirection unexpected
f is null
My code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include<cmath>
using namespace std;
int main(){
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int MAX_BUFFER =2048;
string output;
char fileInput [MAX_BUFFER];
// string input(istreambuf_iterator<char>(cin), {});
string input =" From fairest creatures we desire increase ,\
That thereby beauty's rose might never die,\
But as the riper should by time decease,\
His tender heir might bear his memory:\
But thou contracted to thine own bright eyes,\
Feed'st thy light's flame with self-substantial fuel,\
Making a famine where abundance lies,\
Thy self thy foe, to thy sweet self too cruel:\
Thou that art now the world's fresh ornament,\
And only herald to the gaudy spring,\
Within thine own bud buriest thy content,\
And tender churl mak'st waste in niggarding:\
Pity the world, or else this glutton be,\
To eat the world's due, by the grave and thee.\
When forty winters shall besiege thy brow,\
And dig deep trenches in thy beauty's field,\
Thy youth's proud livery so gazed on now,\
Will be a tattered weed of small worth held:\
Then being asked, where all thy beauty lies,\
Where all the treasure of thy lusty days;\
To say within thine own deep sunken eyes,\
Were an all-eating shame, and thriftless praise.\
How much more praise deserved thy beauty's use,\
If thou couldst answer 'This fair child of mine\
Shall sum my count, and make my old excuse";
string cmd_string = "/bin/bash -c grep -i \"the[^a-z0-9]\" $filename <<< "+input;
//cout<<cmd_string.c_str();
FILE *f=popen(cmd_string.c_str(),"r");
while (!feof(f))
{
if (fgets(fileInput, MAX_BUFFER, f) != NULL)
{
cout<<" line 1"<<fileInput[0];
output+=fileInput;
}
else
{
cout<<"f is null"<<endl;
}
}
pclose(f);
cout<< output;
return 0;
}