我正在使用io.h中的write(fd,buffer,count)將緩衝區寫入文件描述符。如何將寫入緩衝區添加到在io.h中定義的寫入中
現在我發現了巨大的性能問題,因爲每次我調用「寫入」時它都會執行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);
}
};
這對我來說有點高級。你可以看看這個鏈接:http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/filedescriptoroutbuffer.htm。你們都使用streambuf,但實現是不同的。我可以使用鏈接中的那個嗎?但另一個問題是,鏈接無法控制buf的大小。 – performanceuser 2012-02-10 22:14:54
其實,鏈接指向我的另一個版本的代碼! ;)當我翻譯他的德語書時,我原本是爲尼科的書寫的。除了錯誤(上面的代碼沒有經過測試),這大致是相同的,但沒有緩衝區,上面的版本也使用了一些簡潔的技巧。您可以在任一版本中分配合適的緩衝區(具有適當大小的「std :: vector')。尼科的書解釋了怎麼回事:也許你應該看看那裏。 –
2012-02-10 23:05:00
真是巧合。那麼你能告訴我如何將緩衝區添加到鏈接中的代碼?它看起來對我更可讀。 – performanceuser 2012-02-11 01:03:14