c语言getline读取一行命令行,如何从文件的特定行中获取getline()? C ++
這個問題非常不清楚。您如何確定具體
線?如果是第n行,最簡單的解決方案就是調(diào)用
getlinen次,扔掉除最后一個結(jié)果以外的所有結(jié)果;呼喚
ignoren-1次可能會快一點,但我懷疑如果
您總是讀入相同的字符串(而不是構(gòu)造一個
每次都更新一次),時間上的差異不會很大。如果你
還有其他條件,文件確實很大(從您的
描述(不是)并進行排序,則可以嘗試使用二進制搜索,
尋求文件的中間,請?zhí)崆伴喿x以找到
下一行的開始,然后根據(jù)其決定下一步
值。 (我已使用它在日志文件中查找相關(guān)條目。但是
我們正在談?wù)摰奈募笮閹浊д鬃止?jié)。)
如果您愿意使用系統(tǒng)相關(guān)代碼,則可能會有所幫助
內(nèi)存映射文件,然后搜索\'\\ n \'的第n個出現(xiàn)位置
(std::findn次)。
添加:只是一些快速基準測試。在我的Linux機器上,獲取
/usr/share/dict/words起的第100000個字(479623個字,每行一個,
在我的機器上),大約需要
272毫秒,讀取所有單詞
變成std::vector,然后索引,
256毫秒執(zhí)行相同操作,但是
加上std::deque
30毫秒,使用getline,但是
只是忽略結(jié)果,直到
我感興趣的一個
20毫秒使用
istream::ignore,以及
使用mmap和6毫秒
在std::find上循環(huán)播放。
FWIW,每種情況下的代碼是:
對于std ::容器:
template
void Using::operator()()
{
std::ifstream input( m_filename.c_str() );
if ( !input )
Gabi::ProgramManagement::fatal() << \"Could not open \" << m_filename;
Container().swap( m_words );
std::copy( std::istream_iterator( input ),
std::istream_iterator(),
std::back_inserter( m_words ) );
if ( static_cast( m_words.size() ) < m_target )
Gabi::ProgramManagement::fatal()
<< \"Not enough words, had \" << m_words.size()
<< \", wanted at least \" << m_target;
m_result = m_words[ m_target ];
}
對于不保存的getline:
void UsingReadAndIgnore::operator()()
{
std::ifstream input( m_filename.c_str() );
if ( !input )
Gabi::ProgramManagement::fatal() << \"Could not open \" << m_filename;
std::string dummy;
for ( int count = m_target; count > 0; -- count )
std::getline( input, dummy );
std::getline( input, m_result );
}
對于ignore:
void UsingIgnore::operator()()
{
std::ifstream input( m_filename.c_str() );
if ( !input )
Gabi::ProgramManagement::fatal() << \"Could not open \" << m_filename;
for ( int count = m_target; count > 0; -- count )
input.ignore( INT_MAX, \'\\n\' );
std::getline( input, m_result );
}
而對于mmap:
void UsingMMap::operator()()
{
int input = ::open( m_filename.c_str(), O_RDONLY );
if ( input < 0 )
Gabi::ProgramManagement::fatal() << \"Could not open \" << m_filename;
struct ::stat infos;
if ( ::fstat( input, &infos ) != 0 )
Gabi::ProgramManagement::fatal() << \"Could not stat \" << m_filename;
char* base = (char*)::mmap( NULL, infos.st_size, PROT_READ, MAP_PRIVATE, input, 0 );
if ( base == MAP_FAILED )
Gabi::ProgramManagement::fatal() << \"Could not mmap \" << m_filename;
char const* end = base + infos.st_size;
char const* curr = base;
char const* next = std::find( curr, end, \'\\n\' );
for ( int count = m_target; count > 0 && curr != end; -- count ) {
curr = next + 1;
next = std::find( curr, end, \'\\n\' );
}
m_result = std::string( curr, next );
::munmap( base, infos.st_size );
}
在每種情況下,代碼都將運行
總結(jié)
以上是生活随笔為你收集整理的c语言getline读取一行命令行,如何从文件的特定行中获取getline()? C ++的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iphone屏蔽系统更新_iOS13屏蔽
- 下一篇: java简单创建图片面板_图像界面编程简