- _read _read
- Синтаксис Syntax
- Параметры Parameters
- Возвращаемое значение Return Value
- Комментарии Remarks
- Требования Requirements
- ReadFile function (fileapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Synchronization and File Position
- Pipes
- Transacted Operations
- Examples
- Console. Read Метод
- Определение
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
_read _read
Считывает данные из файла. Reads data from a file.
Синтаксис Syntax
Параметры Parameters
демо fd
Дескриптор файла, ссылающийся на открытый файл. File descriptor referring to the open file.
двойной buffer
Место хранения данных. Storage location for data.
buffer_size buffer_size
Максимальное число байтов для чтения. Maximum number of bytes to read.
Возвращаемое значение Return Value
_read возвращает число считанных байтов, которое может быть меньше BUFFER_SIZE , если в файле осталось меньше BUFFER_SIZE байт или если файл был открыт в текстовом режиме. _read returns the number of bytes read, which might be less than buffer_size if there are fewer than buffer_size bytes left in the file, or if the file was opened in text mode. В текстовом режиме каждая пара символов возврата каретки и перевода строки \r\n заменяется одним символом перевода строки \n . In text mode, each carriage return-line feed pair \r\n is replaced with a single line feed character \n . В возвращаемом значении учитывается только один символ перевода строки. Only the single line feed character is counted in the return value. Эта замена не влияет на указатель файла. The replacement does not affect the file pointer.
Если функция пытается прочитать конечную часть файла, она возвращает 0. If the function tries to read at end of file, it returns 0. Если демон не является допустимым, файл не открыт для чтения или файл заблокирован, вызывается обработчик недопустимых параметров, как описано в разделе Проверка параметров. If fd is not valid, the file isn’t open for reading, or the file is locked, the invalid parameter handler is invoked, as described in Parameter Validation. Если выполнение может быть продолжено, функция возвращает значение-1 и устанавливает для значение EBADF. If execution is allowed to continue, the function returns -1 and sets errno to EBADF.
Если параметр buffer имеет значение NULL или BUFFER_SIZE > INT_MAX, вызывается обработчик недопустимых параметров. If buffer is NULL, or if buffer_size > INT_MAX, the invalid parameter handler is invoked. Если выполнение может быть продолжено, функция возвращает значение-1 , а параметру возврата — еинвал. If execution is allowed to continue, the function returns -1 and errno is set to EINVAL.
Дополнительные сведения об этом и других кодах возврата см. в статье _doserrno, errno, _sys_errlist и _sys_nerr. For more information about this and other return codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
Комментарии Remarks
Функция _read считывает максимум BUFFER_SIZE байт в буфер из файла, связанного с демоном. The _read function reads a maximum of buffer_size bytes into buffer from the file associated with fd. Операция чтения начинается с текущего положения указателя файла, связанного с данным файлом. The read operation begins at the current position of the file pointer associated with the given file. После операции чтения указатель файла указывает на следующий непрочитанный символ. After the read operation, the file pointer points to the next unread character.
Если файл был открыт в текстовом режиме, чтение завершается, когда _read встречает символ CTRL + Z, который рассматривается как индикатор конца файла. If the file was opened in text mode, the read terminates when _read encounters a CTRL+Z character, which is treated as an end-of-file indicator. Чтобы очистить индикатор конца файла, следует использовать _lseek. Use _lseek to clear the end-of-file indicator.
По умолчанию глобальное состояние этой функции ограничивается приложением. By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT. To change this, see Global state in the CRT.
Требования Requirements
Подпрограмма Routine | Обязательный заголовок Required header |
---|---|
_read _read |
Дополнительные сведения о совместимости см. в разделе Compatibility. For more compatibility information, see Compatibility.
ReadFile function (fileapi.h)
Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device.
This function is designed for both synchronous and asynchronous operations. For a similar function designed solely for asynchronous operation, see ReadFileEx.
Syntax
Parameters
A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, communications resource, mailslot, or pipe).
The hFile parameter must have been created with read access. For more information, see Generic Access Rights and File Security and Access Rights.
For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept function.
A pointer to the buffer that receives the data read from a file or device.
This buffer must remain valid for the duration of the read operation. The caller must not use this buffer until the read operation is completed.
The maximum number of bytes to be read.
A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
For more information, see the Remarks section.
A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL.
If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.
For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an hFile that does not support byte offsets, Offset and OffsetHigh are ignored.
For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the Synchronization and File Position section.
Return value
If the function succeeds, the return value is nonzero (TRUE).
If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call the GetLastError function.
Remarks
The ReadFile function returns when one of the following conditions occur:
The ReadFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.
To cancel all pending asynchronous I/O operations, use either:
Use CancelSynchronousIo to cancel pending synchronous I/O operations.
I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.
The ReadFile function may fail with ERROR_NOT_ENOUGH_QUOTA, which means the calling process’s buffer could not be page-locked. For additional information, see SetProcessWorkingSetSize.
If part of a file is locked by another process and the read operation overlaps the locked portion, this function fails.
Accessing the input buffer while a read operation is using the buffer may lead to corruption of the data read into that buffer. Applications must not read from, write to, reallocate, or free the input buffer that a read operation is using until the read operation completes. This can be particularly problematic when using an asynchronous file handle. Additional information regarding synchronous versus asynchronous file handles can be found in the Synchronization and File Position section and in the CreateFile reference topic.
Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of the ReadFile function. By default, the console mode is ENABLE_LINE_INPUT, which indicates that ReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, but GetLastError returns ERROR_OPERATION_ABORTED. For more information, see CreateFile.
When reading from a communications device, the behavior of ReadFile is determined by the current communication time-out as set and retrieved by using the SetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, see COMMTIMEOUTS.
If ReadFile attempts to read from a mailslot that has a buffer that is too small, the function returns FALSE and GetLastError returns ERROR_INSUFFICIENT_BUFFER.
There are strict requirements for successfully working with files opened with CreateFile using the FILE_FLAG_NO_BUFFERING flag. For details see File Buffering.
If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:
Synchronization and File Position
Pipes
If a named pipe is being read in message mode and the next message is longer than the nNumberOfBytesToRead parameter specifies, ReadFile returns FALSE and GetLastError returns ERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to the ReadFile or PeekNamedPipefunction.
If the lpNumberOfBytesRead parameter is zero when ReadFile returns TRUE on a pipe, the other end of the pipe called the WriteFile function with nNumberOfBytesToWrite set to zero.
For more information about pipes, see Pipes.
Transacted Operations
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
Technology | Supported |
---|---|
Server Message Block (SMB) 3.0 protocol | Yes |
SMB 3.0 Transparent Failover (TFO) | Yes |
SMB 3.0 with Scale-out File Shares (SO) | Yes |
Cluster Shared Volume File System (CsvFS) | Yes |
Resilient File System (ReFS) | Yes |
В
Examples
For a code example that shows you how to test for end-of-file, see Testing for the End of a File. For other examples, see Creating and Using a Temporary File and Opening a File for Reading or Writing.
Console. Read Метод
Определение
Читает следующий символ из стандартного входного потока. Reads the next character from the standard input stream.
Возвращаемое значение
Следующий символ из входного потока или значение минус единица (-1), если доступных для чтения символов не осталось. The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.
Исключения
Ошибка ввода/вывода. An I/O error occurred.
Примеры
В следующем примере демонстрируется Read метод. The following example demonstrates the Read method.
Комментарии
ReadМетод блокирует свой возврат при вводе входных символов. при нажатии клавиши он завершается Enter . The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Нажатие клавиши Ввод добавляет зависимую от платформы последовательность завершения строк к входным данным (например, в Windows добавляется последовательность возврата каретки и перевода строки). Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Последующие вызовы Read метода получают входные данные по одному символу за раз. Subsequent calls to the Read method retrieve your input one character at a time. После получения последнего символа Read блокирует его возврат, и цикл повторяется. After the final character is retrieved, Read blocks its return again and the cycle repeats.
ReadLineМетод или KeyAvailable свойство и ReadKey метод предпочтительнее использовать Read метод. The ReadLine method, or the KeyAvailable property and ReadKey method are preferable to using the Read method.
Обратите внимание, что метод не возвращает значение-1, если не выполнить одно из следующих действий. Note that the method does not return -1 unless you perform one of the following actions:
Одновременно нажмите клавишу Control -модификатор и Z клавишу консоли (Ctrl + Z), которая сигнализирует о условии завершения файла. Simultaneously press the Control modifier key and Z console key (Ctrl+Z), which signals the end-of-file condition.
Нажмите эквивалентный ключ, который сигнализирует о условии окончания файла, например Клавиша F6 в Windows. Press an equivalent key that signals the end-of-file condition, such as the F6 function key in Windows.
Перенаправьте входной поток в источник, например текстовый файл, который содержит фактический символ конца файла. Redirect the input stream to a source, such as a text file, that has an actual end-of-file character.