Използвам write(fd, buffer, count) в io.h за запис на буфер във файлов дескриптор.
Сега открих огромен проблем с производителността, защото всеки път, когато извикам "write", той ще извърши IO операция.
Искам да добавя буфер, преди действително да запиша съдържание във файл.
Кой е най-добрият начин да направите това?
Търсих и намерих това:
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);
}
};