![](/img/trans.png)
[英]How to read a file using boost::iostreams::file_descriptor_source?
[英]How does the read function in boost::iostreams::source actually work?
我正在研究boost :: iostreams,並且試圖編寫自己的源設備。 我寫了兩個版本的boost :: source。 在第一個版本中,我只是將時間字符串復制到s,並且它起作用了。 但是在第二個版本中,我復制了一個特定的字符串,它將不起作用,當我在此處創建斷點時,我發現它是一個圓。
struct mysource{
typedef char char_type;
typedef io::source_tag category;
mysource(const char * echo):m_echo(echo){}
std::streamsize read(char_type * s, std::streamsize n)
{
time_t tm;
::time(&tm);
//return strlen(strncpy(s,ctime(&tm),n-1)); version 1 make a breakpoint here
//return strlen(strncpy(s, m_echo, n-1)); version 2
}
private:
const char * m_echo;
};
這是測試。
int main(int argc, char * argv[])
{
string s;
const char * echo = "Hello world";
io::stream<mysource> in(echo);
getline(in, s);
cout << s << endl;
}
版本1:輸出正確,版本2:死圈。
所以我很困惑,“ read”調用中的工作流程是什么?
我略過了boost :: iostreams的用法。 我發現這些示例有些復雜,在我看來,這些示例在設備類中添加了一些成員。 而且基本功能似乎沒有必要,因為我的版本1可以正確運行。
在對boost :: iostreams和上面提到的圈子進行了一些研究之后,我發現我應該為“讀取”功能實現一個計數器。 計數器會告訴系統何時停止,因為“讀取”功能將被調用多次。
struct mysource{
typedef char char_type;
typedef io::source_tag category;
mysource(const char * echo):m_echo(echo), pos_(0){}
std::streamsize read(char_type * s, std::streamsize n)
{
int left = strlen(m_echo) - pos_;
int len = std::min((int)n, left);
if(len != 0){
int ret = strlen(strncpy(s, m_echo + pos_, len));
pos_ += ret;
return ret;
}
else{
return -1; //EOF
}
}
private:
const char * m_echo;
private:
std::streamsize pos_;
};
現在可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.