Получение значений c ++ из вывода awk

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

Я использовал эту строку в своем коде c ++ для подсчета некоторых строк в out.txt. это печать правильно, я ценю. теперь мне нужно использовать это я считать значение в с ++. Может ли кто-нибудь помочь мне сделать это.

2

Решение

Вам нужно использовать popen, вместо system,

посмотреть здесь: http://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html

Это как нечто среднее между fopen () и system (), он «возвращает» вывод системного вызова в виде канала в стиле Unix, который очень похож на FILE *.

1

Другие решения

Я думаю, что часть меня только что умерла внутри. Следующий код 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 $]
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector