文件读取

1.      用ifstream打开文件

ifstreamifile(m_szFilename,ios::in|ios::binary);

如果不加ios::binary,默认为文本方式打开,如果读出的内容要存入数组会容易出现一些问题,如“屯屯屯”。

 

2.      获取文件长度

ifile.seekg(0,ios::end);  //指向文件末尾
m_nLength = ifile.tellg();
ifile.seekg(0);   //获取完后再返回开头

3.      分配一段空间

<pre name="code" class="cpp">m_pData = new unsigned char[m_nLength+1];
m_pData[m_nLength] = '\0';  //注意最后一位赋0,最好用memset使得整个数组都为0

//读取
while( !ifile.eof() )
{
       ifile.read((char*)m_pData,m_nLength);
       /*
       如要每次读一行,则:
       stringline;
       getline(ifile,line,’\n’)
       */
}



4.      关闭文件

ifile.close();


你可能感兴趣的:(ios)