繁体   English   中英

从awk输出获取C ++值

[英]Getting c++ values from awk output

system("awk 'BEGIN {i=0;}$0 ~/^D/ { i++; printf "i";}END {}' out.txt"); 

我在C ++代码中使用了这一行来计算out.txt中的某些行。 它打印正确的我的价值。 现在我需要使用这个计算C ++中的值。 谁能帮我做到这一点。

您需要使用popen而不是system

参见此处: http : //pubs.opengroup.org/onlinepubs/009696799/functions/popen.html

这就像fopen()和system()之间的交叉,它以unix样式的管道“返回”系统调用的输出,这与FILE *非常相似。

我想我的一部分死在里面。 以下c ++代码将为您计算行数:

#include <iostream>
#include <fstream>


int line_count(const char * fname)
{
  std::ifstream input(fname); 
  int count=0; 
  if(input.is_open()){
    std::string linebuf; 

    while(1){
      std::getline(input, linebuf); 
      if(input.eof()){
    break;
      }
      count++;
    }
  }else{
    return -1; 
  }

  return count; 
}

int main(int argc, char * argv[])
{
  int total=0; 
  for(int i=1; i!=argc; i++){
    int rv=line_count(argv[i]);
    if(rv<0){
      std::cerr<<"unable to open file: "<<argv[i]<<std::endl;
    }else{
      std::cout<<"file "<<argv[i]<<" contains "<<rv<<" lines"<<std::endl;
      total+=rv; 
    }
  }
  std::cout<<"Total number of lines = "<<total<<std::endl;

  return 0; 
} 

(请注意,没有test4文件,只是为了显示错误报告)

[wc-l $] ./count_lines test1 test2 test3 test4
file test1 contains 8 lines
file test2 contains 13 lines
file test3 contains 16 lines
unable to open file: test4
Total number of lines = 37
[wc-l $] 

这与wc -l输出相同:

[wc-l $] wc -l test1 test2 test3 test4
 8 test1
13 test2
16 test3
wc: test4: No such file or directory
37 total
[wc-l $]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM