Skip to content

Instantly share code, notes, and snippets.

@tanitanin
Last active December 27, 2015 05:49
Show Gist options
  • Save tanitanin/7277108 to your computer and use it in GitHub Desktop.
Save tanitanin/7277108 to your computer and use it in GitHub Desktop.
popenをfstreamっぽく使うためのラッパー
#pragma once
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
class invalid_command : std::runtime_error {
public:
invalid_command(const std::string &cause)
: std::runtime_error(cause) {}
};
class pipestream : public std::iostream {
public:
pipestream(const char *path, const char *type);
pipestream(const pipestream &p);
~pipestream();
private:
pipestream();
public:
int get();
pipestream &put(char c);
private:
std::shared_ptr<FILE> _file_ptr;
};
pipestream::pipestream(const char *path, const char *type) {
_file_ptr = std::shared_ptr<FILE>(popen(path, type));
if(&*_file_ptr == nullptr) {
throw invalid_command("popen");
}
}
pipestream::pipestream(const pipestream &p) {
_file_ptr = p._file_ptr;
}
pipestream::~pipestream() {
if(_file_ptr.unique()) pclose(&*_file_ptr);
}
int pipestream::get() {
return std::fgetc(&*_file_ptr);
}
pipestream &pipestream::put(char c) {
std::fputc(c, &*_file_ptr);
return *this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment