C/C++ sstream和fstream

ostringstream
#include <string>
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    ostringstream ostr1;
    ostr1 << "123" << endl;//换行也加入
    cout << ostr1.str();
    long curPos = ostr1.tellp(); //返回当前插入的索引位置(即put pointer的值)
    cout << "curPos = " << curPos << endl;
    ostr1.seekp(4);     // 设置put pointer的值
    ostr1.put('g');     // 在put pointer的位置上写入'g',并将put pointer指向下一个字符位置
    cout << ostr1.str() << endl;
    ostr1.clear();
    string ss = ostr1.str();
    const char *buffer = ss.c_str();
    cout << buffer << endl;
    return 0;
}
fstream
#include <fstream>
#include <regex>
#include <streambuf>
#include <string>
#include <vector>

struct Substitution {
  std::basic_regex<char> regex;
  std::string replacement;
};

// Simple app that does a regex search-and-replace on a template
// and outputs the result.
//
// To invoke:
// expand_template
// --template PATH
// --output PATH
// regex0;replacement0
// regex1;replacement1
// ...
//
// Since it's only used as a private implementation detail of a rule and not
// user invoked we don't bother with error checking.
int main(int argc, const char** argv) {
  // Parse args.
  const char* template_path = nullptr;
  const char* output_path = nullptr;
  std::vector<Substitution> substitutions;
  for (int i = 1; i < argc; ++i) {
    const char* arg = argv[i];
    if (strcmp(arg, "--template") == 0) {
      template_path = argv[++i];
    } else if (strcmp(arg, "--output") == 0) {
      output_path = argv[++i];
    } else {
      const char* mid = strchr(arg, ';');
      if (mid != nullptr) {
        substitutions.push_back(Substitution{
            std::basic_regex<char>(arg, mid - arg),
            std::string(mid + 1),
        });
      }
    }
  }

  // Read template.
  std::ifstream ifs(template_path);
  std::string str(std::istreambuf_iterator<char>(ifs),
                  (std::istreambuf_iterator<char>()));

  // Apply regexes.
  for (const auto& subst : substitutions) {
    str = std::regex_replace(str, subst.regex, subst.replacement);
  }

  // Output file.
  std::ofstream file(output_path);
  file << str;

  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值