![](/img/trans.png)
[英]boost::iostreams::copy() closes the source but not the sink
[英]How to change read/write method of source/sink device in C++ boost::iostreams?
我正在嘗試熟悉 boost::iostream,所以在我正在編寫的示例程序中,我想從文件中讀取文本並將其寫入文件。
我會使用從 file_source/file_sink 繼承的 class 作為讀取/寫入的設備。 在讀取方法中,我的 class 需要每個字符加一個,寫入方法需要每個字符減一個。
首先,我要確保程序的閱讀部分可以正常工作,以便您可以看到如下代碼:
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include "MyFileSource.h"
#include <iostream>
using namespace std;
using namespace boost::iostreams;
int main()
{
MyFileSource<char> fileSource("source.txt");
stream<MyFileSource<char>> myStream(fileSource);
std::cout << myStream.rdbuf();
fileSource.close();
}
我繼承的源設備代碼如下:
template <typename charType>
class MyFileSource : public boost::iostreams::file_source
{
public:
MyFileSource(const std::string& path) : boost::iostreams::file_source(path)
{
file_path = path;
if (!is_open())
open(path);
seek(0, ios::end);
sizeOfFile = seek(0, ios::cur);
seek(0, ios::beg);
buffer = new charType[sizeOfFile];
}
std::streamsize read(charType*, std::streamsize)
{
std::streamsize readCount = boost::iostreams::file_source::read(buffer, sizeOfFile);
if (readCount > 0)
{
std::string result(buffer, readCount);
for (char& c : result)
c++;
finalResult = result;
}
return readCount;
}
private:
string file_path;
int sizeOfFile;
charType* buffer;
std::string finalResult;
};
不幸的是,使用上述讀取方法的std::cout << myStream.rdbuf()的結果是什么,而如果我刪除 MyFileSource class 的讀取方法以使用父級的讀取方法,結果將是正確的。
任何幫助將不勝感激。
我解決了問題...
template <typename charType>
class MyFileSource : public boost::iostreams::file_source
{
public:
MyFileSource(const std::string& path) : boost::iostreams::file_source(path)
{
if (!is_open())
open(path);
}
std::streamsize read(charType* s, std::streamsize n)
{
std::streamsize readCount = boost::iostreams::file_source::read(s, n);
if (readCount > 0)
{
std::string result(s, readCount);
for (auto& c : result)
c++;
std::copy(result.begin(), result.end(), s);
}
return readCount;
}
};
如您所見,通過刪除額外的緩沖區變量並將其替換為 s 解決了問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.