use the wc console command to list the number of words in a
specified file, after the user has entered the file's name. How
can this be done?
On Linux, and with in my C++ programs, I use popen. Here is a snippet of code (part of class Metric_v05) which compiles.
// retrieve what wc reports
void Metric_v05::getRawLocCount (std::string aPfn,
uint32_t& lineCount,
uint32_t& wordCount,
uint32_t& byteCount)
{
std::string cmd;
cmd = "wc " + aPfn;
// use pipe to invoke the command and retrieve results
FILE* pipe = popen(cmd.c_str(), "r");
do
{
if(0 == pipe) break; // skip over pclose()
std::stringstream ss;
{
char buff[1024]; // assume all these lines will be shorter than this (C-ism)
memset(buff, 0, 1024);
// read output from pipe
if (0 == fgets(buff, 1024, pipe))
{
// break out when no more output at pipe
std::cout << "line word byte ?" << std::endl;
pclose(pipe);
break; // queue complete, eof, kick out
}
ss << buff;
}
// output of wc / input to the buff is "line word byte", such as:
// 1257 4546 44886
ss >> lineCount >> wordCount >> byteCount;
// TBR - stat = ss >> xxx; if(!stat) break;
// I would normally recommend status check,
// but wc is quite reliable.
if (false) // diagnostic disabled
std::cout << "lwb: "
<< lineCount << " "
<< wordCount << " "
<< byteCount << std::endl;
// be sure to
pclose(pipe);
} while (0); // only 1 line to fetch, drop any others.
} // void Metric_v05::getRawLocCount (...)
system(cmd1)system(cmd1.c_str())int system( const char * syscom );, notsystem(std::string)