多线程fstream带文件锁写数据

#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/file.h>
#include <string.h>

 int m_nCountMember;
 vector <string> vectData;
 inline void PutInt(string &str,int nCount)
 {
  char szBuffer[1024] = {0};
  sprintf(szBuffer,"%d",nCount );
  str += szBuffer;
 }
 inline void PutInt(string &str,string strData)
 {
  str += strData;
 }

bool  Print(CRole* pRole,string filename)
{
 if (NULL == pRole)
  return false;
 string strData;
 PutInt(strData, pRole->account_name);
 PutInt(strData, "\t");
 PutInt(strData, pRole->role_name);
 PutInt(strData, "\t");
 PutInt(strData, pRole->m_nRoleCreateTime);
 PutInt(strData, "\t");
 PutInt(strData, pRole->m_nOnline);
 PutInt(strData, "\t");
 PutInt(strData, pRole->m_nLastOnlineTime);
 PutInt(strData, "\t\t");
 PutInt(strData, pRole->m_nRolePetMaxLv);
 PutInt(strData, "\t");
 PutInt(strData, 0);
 vectData.push_back(strData);
 m_nCountMember++;
 if (m_nCountMember % 20000 == 0 && 0 < m_nCountMember)
 {
  ofstream saveMebbers;
  string Logname = filename + "Log.txt";
  ofstream saveLog(Logname.c_str(), ios::app);
  saveLog << "线程" << m_nID + 1 << "玩家数据" << m_nCountMember<< endl;
  saveMebbers.open(m_strfilename.c_str(), ios::app);
  if (!saveMebbers)
  {
   saveLog << "线程" << m_nID + 1 << "打开文件" << m_strfilename << "失败" << endl;
   return false;
  }
  int nfd = open(m_strfilename.c_str(), O_WRONLY | O_CREAT);
  flock(nfd, LOCK_EX);
  for (int i = 0; i < vectData.size(); i++)
   saveMebbers << vectData[i] << endl;
  flock(nfd, LOCK_UN);
  vectData.clear();
  saveMebbers.close();
 }
 return true;

原文地址:https://www.cnblogs.com/byfei/p/3112332.html