_read

从文件读取数据。

语法

int _read(
   int const fd,
   void * const buffer,
   unsigned const buffer_size
);

参数

fd
引用打开的文件的文件说明符。

buffer
数据的存储位置。

buffer_size
要读取的最大字节数。

返回值

_read 返回读取的字节数,如果文件中剩余的字节数少于 buffer_size,或者文件以文本模式打开,则读取的字节数可能会少于 buffer_size。 在文本模式下,会将每个回车换行符对 \r\n 替换为换行符 \n。 在返回值中仅计算单个换行符。 此替换不影响文件指针。

如果函数尝试在文件末尾进行读取,则返回 0。 如果 fd 无效、未打开供读取的文件或文件被锁定,则将调用无效的参数处理程序,如参数验证中所述。 如果允许执行继续,则该函数将返回 -1 并将 errno 设置为 EBADF

如果 bufferNULL,或者 buffer_size>INT_MAX,则会调用无效的参数处理程序。 如果允许执行继续,则函数将返回 -1 并将 errno 设置为 EINVAL

有关这代码和其他返回代码的详细信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

备注

_read 函数从与 fd 相关联的文件将最大 buffer_size 字节读入 buffer。 读取操作从与给定文件相关联的文件指针的当前位置开始执行。 读取操作完成后,文件指针将指向下一个未读取的字符。

如果文件是在文本模式下打开的,则在 _read 遇到 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

另请参阅

低级别 I/O
_creat_wcreat
fread
_open_wopen
_write