将文件格式化并输出

来源:互联网 发布:知乎怎么补充回答 编辑:程序博客网 时间:2024/06/06 11:42


我们是搞运维的。由于要放假了 需要知道磁盘的使用情况,所以将df -h好多服务器的结果输出到一个文件中,再写个c++程序过滤之。df -h 的文件列表格式如下:

10.109.10.1
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2              15G   2.4G   12G  18% /
/dev/sda1              99M   12M   82M  13% /boot
tmpfs                     32G     0     32G     0% /dev/shm
/dev/sda5             200G  175G  25G  87.5% /opt

10.109.10.2

Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2              15G  2.4G   12G  18% /
/dev/sda1              99M   12M   82M  13% /boot
tmpfs                    32G     0   32G   0% /dev/shm
/dev/sda5             200G  175G  25G  87.5% /opt

10.109.10.3

..........


..............


................

就想把 ip  和 想了解剩余磁盘空间那行输出到文件中,这样看起来一目了然。

 cat fileop.cpp

#include<iomanip>
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
void GrepAndWrite(ifstream &fs)
{
  char* s;
  s = new char[160];
  string str="";
  string searchip = "10.1";
  string searchuse3="opt";
  string strip;
  string struse;
  ofstream fo ("/opt/test/diskproc",ios::app);
  while (! fs.eof() )
  {
     fs.getline(s,100);
     //cout<<s<<std::endl;
     str = s;
     //strip=""; struse="";
     if(str.find(searchip) !=string::npos)
     {
       strip=str;
     }
     else
     {
       if(str.find(searchuse3)!=string::npos )
       {
           if(strip!="")
           {
             struse=str;
           }
       }
     }

     if(strip !="" && struse !="")
     {
       //strip=""; struse="";
       //write file
       {
          fo<<strip <<" "<< struse<<std::endl;
       }
       strip=""; struse="";
     }
  }
  fo.close();
}

int main()
{
  ifstream fread("/opt/test/diskinfo",ios::out);
  if(!fread.is_open())
  {
     std::cout<<"file open fail~"<<std::endl;
     return 0;
  }
  else
  {
     GrepAndWrite(fread);
  }
  fread.close();
 
  return 0;
}
0 0