从C ++调用"cat"的简单方法? [英] Simple way to call 'cat' from c++?

查看:118
本文介绍了从C ++调用"cat"的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些C ++代码,并且需要根据文件的内容预先分配一个数组.我绝对可以读取文件并以某种方式解析字符串,但是必须更容易从以下Linux单行代码中找到正确的数字:

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

从C ++代码中在文件上使用此单个衬纸的最佳方法是什么?

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

推荐答案

使用< stdio.h> 中的 popen :

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);
}

popen 的返回值是标准的I/O流,就像 fopen 返回的那样.但是,您应该使用 pclose 而不是 fclose 来关闭流.

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.

这篇关于从C ++调用"cat"的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆