標準庫readsome沒有讀出任何數據

問題

使用readsome讀取文件,沒有任何數據返回,代碼片斷如下:

std::ifstream infile;
infile.open(m_strFileName, std::ios_base::in | std::ios_base::binary);
if (!infile.is_open())
{
	return false;
}

char szBuffer[512] = { 0 };
std::streamsize nReadBytes = infile.readsome(szBuffer, sizeof(szBuffer));;

原因分析及解決

This unformatted input function extracts up to count elements from the input stream and stores them in the array str.This function does not wait for input. It reads whatever data is available.

以上是從MSDN中找到的,原來這個函數是一個非阻塞函數,輸入緩衝區爲空時,它不會等待,直接就返回,此時可能沒有任何數據。

如果是讀取文件,這個緩衝區一直是空的,我想大概是要調用下read纔會觸發真正讀取文件吧,所以讀取文件不要用這個函數。以下是我讀取文件全部內容的片斷代碼:

std::ifstream infile;
infile.open(m_strFileName, std::ios_base::in | std::ios_base::binary);
if (!infile.is_open())
{
	return false;
}

char szBuffer[512] = { 0 };
do 
{
	infile.read(szBuffer, sizeof(szBuffer));
	nReadBytes = infile.gcount();
	if (nReadBytes > 0)
	{
		//自己封裝的一個裝數據的類,將讀取到的字節加到此類對象中
		pDataPacker->WriteBuffer( (unsigned char*)szBuffer, (int)nReadBytes);
	}
} while ( infile.good() );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章