好的,这里有一些代码概述了我想要做的事情。
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <iostream>
#include <sstream>
int main( int c, char *v[] )
{
int fd = open( "data.out", O_RDONLY | O_NONBLOCK );
std::cout << "fd = " << fd << std::endl;
char buffer[ 1024000 ];
ssize_t nread;
std::stringstream ss;
while( true )
{
if ( (nread = read( fd, buffer, sizeof( buffer ) - 1 )) < 0 )
break;
ss.write( buffer, nread );
while( true )
{
std::stringstream s2;
std::cout << "pre-get : " <<
(((ss.rdstate() & std::ios::badbit) == std::ios::badbit) ? "bad" : "") << " " <<
(((ss.rdstate() & std::ios::eofbit) == std::ios::eofbit) ? "eof" : "") << " " <<
(((ss.rdstate() & std::ios::failbit) == std::ios::failbit) ? "fail" : "" ) << " " <<
std::endl;
ss.get( *s2.rdbuf() );
std::cout << "post-get : " <<
(((ss.rdstate() & std::ios::badbit) == std::ios::badbit) ? "bad" : "") << " " <<
(((ss.rdstate() & std::ios::eofbit) == std::ios::eofbit) ? "eof" : "") << " " <<
(((ss.rdstate() & std::ios::failbit) == std::ios::failbit) ? "fail" : "" ) << " " <<
std::endl;
unsigned int linelen = ss.gcount() - 1;
if ( ss.eof() )
{
ss.str( s2.str() );
break;
}
else if ( ss.fail() )
{
ss.str( "" );
break;
}
else
{
std::cout << s2.str() << std::endl;
}
}
}
}
它首先将大块数据读入数据缓冲区。我知道有更好的C++方法来完成此部分,但在我的实际应用程序中,我会得到一个char[]缓冲区和一个长度。
然后,我将缓冲区写入std::stringstream对象中,以便可以逐行删除它。
我想使用stringstream上的get( streambuf& )方法将一行写入另一个stringstream,然后输出它。
忽略从已读取的缓冲区中提取每行的最佳方法可能不是这种方法(尽管我希望任何人都能提供比我发布的更好的替代方案),但只要第一个
ss.get(*s2.rdbuf())
被调用,ss
就处于失败状态,我无法弄清楚原因。输入文件中有大量数据,因此ss
肯定包含多行输入。有什么想法吗?