簡介
函數原型
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);
程序說明:此程序未指定數據個數,而默認為全部數據,所以顯示了文件中的所有數據。