_read
從檔案讀取資料。
語法
int _read(
int const fd,
void * const buffer,
unsigned const buffer_size
);
參數
fd
參考已開啟檔案的檔案描述項。
buffer
資料的儲存位置。
buffer_size
要讀取的位元組數目上限。
傳回值
_read
會傳回讀取的位元組數目,如果檔案中還剩少於buffer_size
位元組,或檔案是以文字模式開啟,則可能會小於buffer_size
。 在文字模式中,每一個歸位字元換行字元\n
會取代每一個歸位字元\r\n
。 傳回值中只會計算單一換行字元。 取代不會影響檔案指標。
如果函式嘗試讀取檔案的結尾,則會傳回 0。 如果fd
無效,則檔案未開啟以供讀取,或檔案已鎖定,則會叫用無效的參數處理程式,如參數驗證中所述。 如果允許繼續執行,則函式會傳回 -1 並將 errno
設定為 EBADF
。
如果 buffer
為 NULL
,或 如果 buffer_size
>INT_MAX
為 ,則會叫用無效的參數處理程式。 如果允許繼續執行,此函式會傳回 -1,並將 errno
設為 EINVAL
。
如需此傳回碼和其他傳回碼的詳細資訊,請參閱errno
、 _sys_errlist
_doserrno
和 _sys_nerr
。
備註
函_read
式會從與fd
相關聯的檔案讀取到 的位元組buffer
數上限buffer_size
。 讀取作業會從與指定檔案相關之檔案指標的目前位置開始。 讀取作業之後,檔案指標會指向下一個未讀取的字元。
如果以文字模式開啟檔案,讀取會在 _read
遇到 CTRL+Z 字元時終止,CTRL+Z 字元被視為檔案結尾指標。 使用 _lseek
來清除檔尾指標。
根據預設,此函式的全域狀態會限定於應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。
需求
常式 | 必要的標頭 |
---|---|
_read |
<io.h> |
如需相容性詳細資訊,請參閱相容性。
程式庫
所有版本的 C 執行階段程式庫。
範例
// crt_read.c
/* This program opens a file named crt_read.txt
* and tries to read 60,000 bytes from
* that file using _read. It then displays the
* actual number of bytes read.
*/
#include <fcntl.h> /* Needed only for _O_RDWR definition */
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
#include <share.h>
char buffer[60000];
int main( void )
{
int fh, bytesread;
unsigned int nbytes = 60000;
/* Open file for input: */
if ( _sopen_s( &fh, "crt_read.txt", _O_RDONLY, _SH_DENYNO, 0 ))
{
perror( "open failed on input file" );
exit( 1 );
}
/* Read in input: */
if (( bytesread = _read( fh, buffer, nbytes )) <= 0 )
perror( "Problem reading file" );
else
printf( "Read %u bytes from file\n", bytesread );
_close( fh );
}
輸入︰crt_read.txt
Line one.
Line two.
輸出
Read 19 bytes from file