报文解析

来源:互联网 发布:json对象合并 编辑:程序博客网 时间:2024/03/29 08:15
操作文件:c++ 标准文件编程库、低级文件编程库
报文解析
读取passwd中的用户名
#include <iostream>
#include <fcntl.h>
using namespace std;


int main()
{
     int fd1 = open("/etc/passwd", O_RDONLY);
     if(fd1 < 0)
     {
cout<<"open passwd fail"<<endl;
return -1;
     }
     int fd2 = open("copyname.txt", O_WRONLY|O_CREAT, 0777);
     if(fd2 < 0)
     {
close(fd1);
cout<<"open copyname fail"<<endl;
return -1;
     }


     char ch;
     int flag = 0;//设置标志位,判断是否是第一次遇到‘:’


     while(read(fd1, &ch, 1) > 0)
     {
if(flag == 0)
{
   if(ch != ':')
   {
write(fd2, &ch, 1);
cout<<ch;
   }
   else
       flag = 1;
}
else
{
   if(ch == '\n')
   {
flag = 0;
write(fd2, &ch, 1);
cout<<ch;
   }


}


     }


     close(fd1);
     close(fd2);
}


读取passwd中的用户名和uid
读一行时用标准文件编程库
#include <iostream>
#include <fstream>
using namespace std;


int main()
{
    char* p1 = NULL;
    char* p2 = NULL;
    char buf[1024]={};


    ifstream fin("/etc/passwd");
    ofstream fout("copynameid.txt", ios:app);


    while(fin.getline(buf, 1024) > 0)
    {
if((p1 = strstr(buf, ":")) == NULL)
    break;
if((p2 = strstr(p1+1, ":")) == NULL)
    break;
++p1;
++p2;


while(*p2 != ':')
{
    *p1 = *p2;
    ++p1;
    ++p2;
}
*p1 = 0;


cout<<buf<<endl;
fout.write(buf, 1024);
memset(buf, 0, 1024);


    }


    fin.close();
    fout.close();
}
原创粉丝点击