Last active
December 27, 2015 05:49
-
-
Save tanitanin/7277108 to your computer and use it in GitHub Desktop.
popenをfstreamっぽく使うためのラッパー
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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