Hi, I have a question regarding the popen() function in C.
I would like to open a text file and count the "the" words, and this would do the job:
Now i would like to read the file name,"myfile.txt", from the standard input as a string and pass it to the popen() function.
fin=popen("cat myfile.txt | grep -o -w 'the' |wc -w ","r");
For example i would like to have something like:
Is there any way i could do this?I know this doesn't work because Shell tries to open the file named 'filename'.
fin=popen("cat filename | grep -o -w 'the' |wc -w ","w"))==NULL);
You could use sprintf to first create the string to pass as an argument to popen, but I wonder why you don't just write a shell script.
By the way, you should avoid gets as it is vulnerable to buffer overflow. You could use fgets instead.
Thanks for the reply :)
Well, I have to do a project using POSIX threads in C, each thread has to count the number of occurrences of the "the" word in a given file. I chose to do this with popen because it's easier and you don't have to code that much :))
Anyway, i tried using sprintf and it's basically the same deal:
And then, when I execute it:
sprintf(file_to_open, "/home/me/Documents/ %s", filename);
fin=popen("cat file_to_open | grep -o -w 'the'|wc -w ","w")
cat: file_to_open: No such file or directory
Am I missing something?
I am thinking more of something like this:
char count_command[FILENAME_MAX + 50];
sprintf(count_command, "cat /home/me/Documents/%s | grep -o -w 'the' |wc -w", filename);
fin = popen(count_command, "w");
That does make sense! How could I have missed that!? :-))
Thanks a lot *hug*
I am use grep very intensive, but somehow never noted -w flag before.
What never fail to astonish me, why so often used
Instead of plain
"cat file | grep ...