Я использую write(fd, buffer, count) в io.h для записи буфера в файловый дескриптор.
Теперь я обнаружил огромную проблему с производительностью, потому что каждый раз, когда я вызываю «запись», он выполняет операцию ввода-вывода.
Я хочу добавить буфер перед записью содержимого в файл.
Как лучше всего это сделать?
Я искал и нашел это:
http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/filedescriptoroutbuffer.htm
Должен ли я использовать этот метод и интегрировать его в свой код? Это хороший подход, который я должен использовать?
Но в нем я не вижу, как определить размер буфера.
Ниже приведен окончательный код:
class fdoutbuf : public std::streambuf {
protected:
enum { size = 4096 };
int fd; // file descriptor
char buf_[size];
public:
// constructor
fdoutbuf (int _fd) : fd(_fd) {
setp(this->buf_, this->buf_ + size - 1);
}
protected:
// write one character
virtual int overflow (int c){
if (c != EOF) {
char z = c;
*this->pptr() = z;
this->pbump(1);
}
return this->sync() == -1? EOF: c;
}
virtual int sync(){
if (this->pbase() == this->pptr()) {
return 0;
}
int count(this->pptr() - this->pbase());
int rc = write(fd, this->buf_, count);
this->setp(this->buf_, this->buf_ + size - 1);
return count == rc? 0: -1;
}
};
class fdostream : public std::ostream {
protected:
fdoutbuf buf;
public:
fdostream (int fd) : std::ostream(0), buf(fd) {
rdbuf(&buf);
}
};