[Pin to top] Using C ++ in Linux to obtain the output content of the command line through pipelines

Source: Internet
Author: User

In Linux, you can use C ++ to obtain command line output content through pipelines.

Reprint please explain the source: http://blog.csdn.net/cywosp/article/details/8980898

When using C ++, sometimes we can use the pipeline method to obtain the output content of the executed command. The procedure is as follows:
First, you need to determine the format of the content output by the command you run (the format of the content output by the same command in different operating systems may be different ). Here is an example: I want to get the temporary storage space of the/var directory, measured in KB:

[Root @ localhost/] # Du-sk/var
13532132var
[Root @ localhost/] # Du-sk/var | awk-F ''' {print $1 }'
13532132
From the above output, we can know that the/var directory currently uses 13532132kb, so how can we change the value to ourProgramMedium? For simplicity, I implemented the following functions:

 

Int64_t calculatedirusedcapacity (const STD: string & directoryname) {file * fstream = NULL; char buff [32]; memset (buff, '\ 0', sizeof (buff )); STD: String cmd = "Du-SK" + directoryname; cmd + = "| awk-F ''' {print $1 }'"; // return the value if (null = (fstream = popen (CMD. c_str (), "R") {return 0;} If (null = fgets (buff, sizeof (buff), fstream) {pclose (fstream ); return 0;} STD: strstream SS; SS <Buff; int64_t usedcapacity = 0; SS> usedcapacity; pclose (fstream); // close pipe return usedcapacity ;}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.