如何在C ++程序中简单地使用控制台命令?

时间:2018-08-12 16:19:00

标签: c++

我正在做一个练习,要求用户输入文件名后,使用 wc 控制台命令列出指定文件中的单词数。该怎么办?

这是到目前为止我管理的一些代码:

int main()
{
    string filename;
    string cmd1,cmd2,cmd3;


    cout<<"Please enter a filename: ";
    getline(cin, filename);


    cmd1="wc -l " +filename;        //lines
    cmd2="wc -w " + filename;   //words
    cmd3="wc -c "+filename;   //bytes
    /

    cout<<system("\\cmd1\\")<<endl;   //does not work

    cout<<system("wc -l device_data.txt")<<endl;   //works


    return 0;
}

3 个答案:

答案 0 :(得分:2)

predicates = [test1, test2, test3]; result = array.filter(e => predicates.every(fn => fn(e))); 函数返回一个整数,该整数是已执行的shell的返回值。

您想要获得的命令输出可以通过以下方式完成:

system

您应该在输入源代码之前阅读手册页;)

答案 1 :(得分:0)

这就是我要做的:

std::string f;
cin>>f;

std::string c1 = "wc -l " + f;
std::string c2 = "wc -w " + f;
std::string c3 = "wc -c " + f;

cout<<system(c1.c_str())<<endl;
cout<<system(c2.c_str())<<endl;
cout<<system(c3.c_str())<<endl;

这里是系统将char *作为参数,而您使用的是字符串数据类型。

答案 2 :(得分:0)

  

使用wc console命令列出单词中的单词数   用户输入文件名后指定的文件。怎么样   可以做到吗?

在Linux上以及在我的C ++程序中,我使用popen。这是一个可编译的代码片段(属于Metric_v05类)。

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