以字符串方式操作文件

要在大量文本文件中做查找、替换,用编辑器配合正则表达式可以,但目标子串有几十种,又不想碰AWK、SED,

就写了这个非常简单的工具:读入整个文件内容,以字符串形式保存。之后可以对字符串操作。然后写到文件中。

注意:

1.我处理的文件都在100KB以内,所以读取函数只能对付1M以下的文件(有空再改)

2.主要目的是处理文本文件,但却是以二进制文件模式打开文件的,不会自动修改换行符。

#include <stdexcept>
#include <fstream>

class FileString
{
  std::string m_content;

public:
  FileString()
  {}

  FileString(std::string const & fileName)
  {
    this->load(fileName);
  }

  void load(std::string const & fileName);
  void save(std::string const & fileName) const;

  std::string const getContent() const
  {
    return m_content;
  }

  void setContent(std::string const & s)
  {
    m_content = s;
  }
};

void FileString::load(std::string const & fileName)
{
  std::ifstream ifs(fileName.c_str(), std::ios::in | std::ios::binary);
  if(!ifs){
    throw std::runtime_error(std::string("FileString::load(): can not open file: ") + fileName);
  }
  int const BUF_SIZE = 1024 * 1024;
  char * buf = new char[BUF_SIZE];
  ifs.read(buf, BUF_SIZE);
  int n = ifs.gcount();
  m_content.assign(buf, n);
  delete[] buf;
}

void FileString::save(std::string const & fileName) const
{
  std::ofstream ofs(fileName.c_str(), std::ios::out | std::ios::binary);
  if(!ofs){
    throw std::runtime_error(std::string("FileString::save(): can not open file: ") + fileName);
  }
  ofs.write(m_content.c_str(), m_content.size());
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值