Skip to content
Advertisement

Simple way to call ‘cat’ from c++?

I am writing some C++ code and I need to pre-allocate an array based on the contents of a file. I can definitely read the the file and parse the strings a certain way, but it’s must easier to find the proper number from the following Linux one-liner:

cat myfile.txt | grep 'Freqs ---' | sed 's/Freqs ---//g' | wc -w

What is the best way to use this single one liner on the file from within the C++ code?

Advertisement

Answer

Use popen from <stdio.h>:

FILE *fp;
char buffer[BUFFER_SIZE];

fp = popen("cat myfile.txt | grep 'Freqs ---' | sed 's/Freqs ---//g' | wc -w", "r");
if (fp != NULL)
{
    while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
        printf("%s", buffer);
    pclose(fp);
}

The return value from popen is a standard I/O stream, just like one returned by fopen. However, you should use pclose instead of fclose to close the stream.

Advertisement