简介
函数原型
size_t
fread(void
*buffer,size_t
size,size_t
count,FILE
*stream);
功能:
从一个文件流中读数据,读取count个元素,每个元素size字节。如果调用成功返回值大于count。如不成功,返回实际读取的元素个数,小于count。
参数
buffer
用于接收数据的内存地址,大小至少是size*count字节。
size
单个元素的大小,单位是字节。
count
元素的个数,每个元素是size字节。
stream
输入流
返回值
实际读取的元素个数.如果返回值与count不相同,则可能文件结尾或发生错误。
从ferror和feof获取错误信息或检测是否到达文件结尾。
程序例
#include
#include
int main(void)
{
FILE*stream;
char msg[]="this is a test";
char buf;
if ((stream=fopen("DUMMY.FIL","w+"))==NULL){
fprintf(stderr,"Cannot open output file.n");
return 0;
} /* write some data to the file */
fwrite(msg, 1,strlen(msg)+1, stream); /* sizeof(char)=1 seek to the beginning of the file */
fseek(stream, 0, SEEK_SET); /* read the data and display it */
fread(buf, 1,strlen(msg)+1,stream);
printf("%sn", buf);
fclose(stream);
return 0;
}
MSDN示例
#include
void main( void )
{
FILE *stream;
char list;
int i, numread, numwritten; /* Open file in text mode: */
if( (stream = fopen( "fread.out", "w+t" )) != NULL )
{
for ( i = 0; i < 25; i++ )
list[i] = (char)('z' - i); /* Write 25 characters to stream */
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d itemsn", numwritten );
fclose( stream );
}
else
printf( "Problem opening the filen" );
if( (stream = fopen( "fread.out", "r+t" )) != NULL )
{ /* Attempt to read in 25 characters */
numread = fread( list, sizeof( char ), 25, stream );
printf( "Number of items read = %dn", numread );
printf( "Contents of buffer = %.25sn", list );
fclose( stream );
}
else
printf( "File could not be openedn" );
}
PHP
$handle = fopen ("test.txt", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
PHP函数
(PHP4,PHP5)
fread--读取文件(可安全用于二进制文件)
说明
string fread( int handle, int length )
fread()从文件指针handle读取最多length个字节。该函数在读取完length个字节数,或到达EOF的时候,或(对于网络流)当一个包可用时就会停止读取文件,视乎先碰到哪种情况。
注意
在区分二进制文件和文本文件的系统上(如Windows)打开文件时,fopen()函数的mode参数要加上'b'。
当从网络流或者管道读取时,例如在读取从远程文件或popen()以及proc_open()的返回时,读取会在一个包可用之后停止。这意味着你应该如下例所示将数据收集起来合并成大块。
程序示例
?
$handle = fopen ("test.txt", "rb");
$contents = "";
while (!feof($handle)) {
$contents.=fread($handle, 8192);
}
fclose($handle);
?>
注:如果你只是想将一个文件的内容读入到一个字符串中,用file_get_contents(),它的性能比上面的代码好得多。
MATLAB函数
功能
fread()函数用来从指定文件中读取块数据。
语法
A=fread(fid, count)
A=fread(fid, count, precision)
其中fid为指针所指文件中的当前位置,count指读取的数据个数,precision表示以什么格式的数据类型读取数据。
例子
fid=fopen('alphabet.txt', 'r');
c=fread(fid, 5)'
c=65 66 67 68 69
fclose(fid);
程序说明:alphabet文件中按顺序存储着26个英文字母,读取文件之前要先打开文件,由于未指定读取数据的类型,所以程序指定默认类型为无符号字符型即uchar,65、66、67、68、69代表A、B、C、D、E,文件用完还要记得关闭文件,以便释放指针。
fid=fopen('alphabet.txt', 'r');
c=fread(fid, '*char')'
c=ABCDEFGHIJKLMNOPQRSTUVWXYZ
fclose(fid);
程序说明:此程序未指定数据个数,而默认为全部数据,所以显示了文件中的所有数据。



















