fread读文件读取不全解决方法

fread,对指定长度的文件数据。读取的长度远小于文件的总长度,怎么回事呢?

查MSDN,fopen最后一个参数:

t Open in text (translated) mode.

In this mode, CTRL+Z is interpreted as an end-of-file character on input.

In files opened for reading/writing with "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible.

This is done because using fseek and ftell to move within a file that ends with a CTRL+Z can cause fseek to behave improperly near the end of the file.

Also, in text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output.

When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters.

For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters.

b Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.

If t or b is not given in mode, the default translation mode is defined by the global variable _fmode.

If t or b is prefixed to the argument, the function fails and returns NULL.  

两种模式,默认应该是文本模式t,这个时候fread遇到控制字符就不往后读了。解决方法:

使用binnay mode 这样就能就没有上述问题了,一个简单的例子:

[cpp] view plain copy
  1. FILE* pFile=fopen("fileName","rb");//这里加载一个PE文件  
  2. fseek(pFile, 0, SEEK_END);  
  3. int len = ftell(pFile);  
  4. char* szBuf=new CHAR[len];  
  5. memset(szBuf,0,len);  
  6. fseek(pFile, 0, SEEK_SET);  
  7. int iRead=fread_s(szBuf,len,1,len,pFile); 

原文出自:http://blog.csdn.net/iamoyjj/article/details/6580978

你可能感兴趣的:(C/C++,fread,文件)