报文解析

操作文件: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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值