На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

ReadFile



The ReadFile function reads data from a file, starting at the position indicated by the file pointer. After the read operation has been completed, the file pointer is adjusted by the number of bytes actually read, unless the file handle is created with the overlapped attribute. If the file handle is created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the read operation.

BOOL ReadFile(

HANDLE hFile, // handle of file to read
LPVOID lpBuffer, // address of buffer that receives data
DWORD nNumberOfBytesToRead, // number of bytes to read
LPDWORD lpNumberOfBytesRead, // address of number of bytes read
LPOVERLAPPED lpOverlapped // address of structure for data
);


Parameters

hFile

Identifies the file to be read. The file handle must have been created with GENERIC_READ access to the file.

Windows NT

For asynchronous read operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept functions.

Windows 95

For asynchronous read operations, hFile can be a communications resource, mailslot, or named pipe handle opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by the socket or accept functions. Windows 95 does not support asynchronous read operations on disk files.

lpBuffer

Points to the buffer that receives the data read from the file.

nNumberOfBytesToRead

Specifies the number of bytes to be read from the file.

lpNumberOfBytesRead

Points to the number of bytes read. ReadFile sets this value to zero before doing any work or error checking. If this parameter is zero when ReadFile returns TRUE on a named pipe, the other end of the message-mode pipe called the WriteFile function with nNumberOfBytesToWrite set to zero.
If lpOverlapped is NULL, lpNumberOfBytesRead cannot be NULL.
If lpOverlapped is not NULL, lpNumberOfBytesRead can be NULL. If this is an overlapped read operation, you can get the number of bytes read by calling GetOverlappedResult. If hFile is associated with an I/O completion port, you can get the number of bytes read by calling GetQueuedCompletionStatus.

lpOverlapped

Points to an OVERLAPPED structure. This structure is required if hFile was created with FILE_FLAG_OVERLAPPED.

If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hFile was created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the read operation is complete.
If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure and ReadFile may return before the read operation has been completed. In this case, ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING. This allows the calling process to continue while the read operation finishes. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the read operation.

If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the read operation starts at the current file position and ReadFile does not return until the operation has been completed.
If hFile is not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure. ReadFile does not return until the read operation has been completed.



Return Values

If the function succeeds, the return value is nonzero.
If the return value is nonzero and the number of bytes read is zero, the file pointer was beyond the current end of the file at the time of the read operation. However, if the file was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the return value is FALSE and GetLastError returns ERROR_HANDLE_EOF when the file pointer goes beyond the current end of file.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

ReadFile returns when one of the following is true: a write operation completes on the write end of the pipe, the number of bytes requested has been read, or an error occurs.
If part of the file is locked by another process and the read operation overlaps the locked portion, this function fails.
Applications must not read from nor write to the input buffer that a read operation is using until the read operation completes. A premature access to the input buffer may lead to corruption of the data read into that buffer.

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.
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 may be read by a subsequent call to the ReadFile or PeekNamedPipe function.

When reading from a communications device, the behavior of ReadFile is governed by the current communication timeouts as set and retrieved using the SetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the timeout values. For more information about communication timeouts, see COMMTIMEOUTS.
If ReadFile attempts to read from a mailslot whose buffer is too small, the function returns FALSE and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

If the anonymous write pipe handle has been closed and ReadFile attempts to read using the corresponding anonymous read pipe handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.
The ReadFile function may fail and return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.
The ReadFile code to check for the end-of-file condition (eof) differs for synchronous and asynchronous read operations.

When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero. The following sample code tests for end-of-file for a synchronous read operation:

// attempt a synchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL) ;
// check for eof
if (bResult && nBytesRead == 0, ) {
// we're at the end of the file
}


An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile, or during subsequent asynchronous operation.
If EOF is detected at ReadFile time for an asynchronous read operation, ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.
If EOF is detected during subsequent asynchronous operation, the call to GetOverlappedResult to obtain the results of that operation returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

To cancel all pending asynchronous I/O operations, use the CancelIO function. This function only cancels operations issued by the calling thread for the specified file handle. I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.
The following sample code illustrates testing for end-of-file for an asynchronous read operation:

// set up overlapped structure fields
// to simplify this sample, we'll eschew an event handle
gOverLapped.Offset = 0;
gOverLapped.OffsetHigh = 0;
gOverLapped.hEvent = NULL;

// attempt an asynchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead,
&gOverlapped) ;

// if there was a problem, or the async. operation's still pending ...
if (!bResult)
{
// deal with the error code
switch (dwError = GetLastError())

{
case ERROR_HANDLE_EOF:
{
// we're reached the end of the file
// during the call to ReadFile

// code to handle that
}

case ERROR_IO_PENDING:
{
// asynchronous i/o is still in progress

// do something else for a while
GoDoSomethingElse() ;

// check on the results of the asynchronous read
bResult = GetOverlappedResult(hFile, &gOverlapped,

&nBytesRead, FALSE) ;

// if there was a problem ...
if (!bResult)
{
// deal with the error code
switch (dwError = GetLastError())
{
case ERROR_HANDLE_EOF:
{
// we're reached the end of the file
//during asynchronous operation
}

// deal with other error cases

}
}
} // end case

// deal with other error cases

} // end switch
} // end if


See Also

CancelIo, CreateFile, GetCommTimeouts, GetOverlappedResult, GetQueuedCompletionStatus, OVERLAPPED, PeekNamedPipe, ReadFileEx, SetCommTimeouts, WriteFile


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

ReadFile



Функция ReadFile читает данные из файла, запуск в позиции указывался файловым указателем. После того, как операция чтения будет завершена, файловый указатель скорректирован количеством байтов действительно прочитанных, если файловая ручка не создана перекрытым атрибутом. Если файловая ручка создана для перекрытого ввода и выхода (В/В), приложение должно отрегулировать позицию файлового указателя после операции чтения.

BOOL ReadFile(

РУЧКА hFile, // ручка файла, чтобы читать LPVOID lpBuffer, // адрес буфера, который получает данные DWORD nNumberOfBytesToRead, // количество байтов, чтобы читать LPDWORD lpNumberOfBytesRead, // адрес количества байтов был прочитан LPOVERLAPPED lpOverlapped // адрес структуры для данных
);


Параметры

hFile

Идентифицирует файл, который нужно быть прочитан. Файловая ручка по-видимому создана доступом GENERIC_READ к файлу.

Windows NT

Для асинхронных операций чтения, hFile может быть любой ручкой открытой флагом FILE_FLAG_OVERLAPPED функцией CreateFile, или ручка розетки возвращалась розеткой или принимала функции.

Windows 95

Для асинхронных операций чтения, hFile может быть ресурсом связи, mailslot, или назвавшее ручку трубы открывался флагом FILE_FLAG_OVERLAPPED CreateFile, или ручка розетки возвращалась розеткой или принимала функции. Windows 95 не поддерживает асинхронные операции чтения в дисковых файлах.

lpBuffer

Точки на буфер, которые получают данные прочитанные из файла.

nNumberOfBytesToRead

Определяет количество байтов, которые нужно быть прочитаны из файла.

lpNumberOfBytesRead

Точки на количество байтов были прочитаны. ReadFile УСТАНАВЛИВАЕТ эту величину в нуль перед занятие любой проверки работы или ошибки. Если этот параметр является нулем когда ИСТИНА возврата ReadFile в поименованной трубе, другой конец сообщения-режима трубы был вызван функция WriteFile с nNumberOfBytesToWrite установленное в нуль.
Если lpOverlapped, НЕДЕЙСТВИТЕЛЬНО, lpNumberOfBytesRead не может быть НЕДЕЙСТВИТЕЛЕН.
Если lpOverlapped, не НЕДЕЙСТВИТЕЛЬНО, lpNumberOfBytesRead может быть НЕДЕЙСТВИТЕЛЕН. Если это - перекрытая операция чтения, Вы можете быть прочитаны количество байтов вызывая GetOverlappedResult. Если hFile связан портом завершения В/В, Вы можете быть прочитаны количество байтов вызывая GetQueuedCompletionStatus.

lpOverlapped

Точки на ПЕРЕКРЫТУЮ структуру. Эта структура потребовалась если hFile был создан FILE_FLAG_OVERLAPPED.

Если hFile был открыт FILE_FLAG_OVERLAPPED, lpOverlapped параметр не должен быть НЕДЕЙСТВИТЕЛЕН. Это должно указать на правильную ПЕРЕКРЫТУЮ структуру. Если hFile был создан FILE_FLAG_OVERLAPPED и lpOverlapped НЕДЕЙСТВИТЕЛЕН, функция может неправильно сообщить, что операция чтения завершенна.
Если hFile был открыт FILE_FLAG_OVERLAPPED и lpOverlapped не НЕДЕЙСТВИТЕЛЕН, операция чтения начинается в смещении определенном в ПЕРЕКРЫТОЙ структуре и ReadFile может возвращаться прежде, чем операция чтения будет завершена. В этом случае, ЛОЖЬ возврата ReadFile и функциональный возврат GetLastError ERROR_IO_PENDING. Это позволяет разговор процесса, чтобы продолжать тогда как операция чтения завершается. Событие определенное в ПЕРЕКРЫТОЙ структуре установлено в сигнальное состояние операции чтения.

Если hFile не был открыт FILE_FLAG_OVERLAPPED и lpOverlapped НЕДЕЙСТВИТЕЛЕН, операция чтения начинается в текущей файловой позиции и ReadFile не возвращается пока операция не завершена.
Если hFile не открыт FILE_FLAG_OVERLAPPED и lpOverlapped не НЕДЕЙСТВИТЕЛЕН, операция чтения начинается в смещении определенном в ПЕРЕКРЫТОЙ структуре. ReadFile НЕ возвращается пока операция чтения не завершена.



Обратные Величины

Если функция добивается успеха, обратная величина ненулевая.
Если обратная величина ненулевая и количество чтения байтов является нулем, файловый указатель превышал текущий конец файла на момент операции чтения. Тем не менее, если файл был открыт FILE_FLAG_OVERLAPPED и lpOverlapped не НЕДЕЙСТВИТЕЛЕН, обратная величина - ЛОЖЬ и возврат GetLastError ERROR_HANDLE_EOF когда файловый указатель превосходит текущим концом файла.
Если функция терпит неудачу, обратная величина нулевая. Для того, чтобы расширять информацию ошибки, вызовите GetLastError.

Замечания

ReadFile ВОЗВРАЩАЕТСЯ когда одно из следующего - истина: записывать операция завершается в записывать конце трубы, количество запрошенных байтов прочитано, или ошибка происходит.
Если часть файла заперта другим процессом и операция чтения перекрывает закрытую часть, эта функция терпит неудачу.
Приложения по-видимому не прочитаются из ни записываются в входной буфер, что операция чтения использует пока операция чтения не завершится. Преждевременный доступ к входному буферу может провести к коррупции данных прочитанных в этот буфер.

Символы могут быть прочитаны из консольного входного буфера используя ReadFile с ручкой, чтобы утешать ввод. Консольный режим определяет точное поведение функции ReadFile.
Если поименованная труба прочитанн в режиме сообщения и следующее сообщение более длинное чем параметр nNumberOfBytesToRead определяется, ЛОЖЬ возврата ReadFile и возврат GetLastError ERROR_MORE_DATA. Разность сообщения возможно прочитана последующим вызовом в ReadFile или функцию PeekNamedPipe.

При чтении с устройства связи, поведение ReadFile управлялось текущими тайм-аутами связи как установлено и извлечено используя SetCommTimeouts и функции GetCommTimeouts. Непредсказуемые результаты могут произойти если Вы не устанавливаете время простоя. Более подробно о тайм-аутах связи, смотри COMMTIMEOUTS.
Если попытки ReadFile, чтобы читаться из mailslot чей буфер слишком небольшое, функция возвращает ЛОЖЬ и возврат GetLastError ERROR_INSUFFICIENT_BUFFER.

Если анонимная записывать ручка трубы закрыта и попытки ReadFile, чтобы читать используя соответствующую ручку трубы анонимного чтения, функциональная ЛОЖЬ возврата и возврата GetLastError ERROR_BROKEN_PIPE.
Функция ReadFile может потерпеть неудачу и возвращать ERROR_INVALID_USER_BUFFER или ERROR_NOT_ENOUGH_MEMORY всякий раз, когда есть слишком много выдающиеся асинхронные запросы В/В.
Код ReadFile, чтобы проверять на наличие конца--файлового условия (eof), отличается для синхронных и асинхронных операций чтения.

Когда синхронная операция чтения достигает конца файла, ИСТИНЫ возврата ReadFile и комплекты *lpNumberOfBytesRead в нуль. Следующий код образца тестирует для конца--файла для синхронной операции чтения:

// попытка синхронная операция чтения bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, НЕДЕЙСТВИТЕЛЬНОЕ);
// чек eof
если (bResult && nBytesRead == 0, ) { // мы - в конце файла
}


Асинхронная операция чтения может столкнуться с концом файла в течение вводящего вызова на ReadFile, или в течение последующей асинхронной операции.
Если EOF обнаружен во времени ReadFile для асинхронной операции чтения, ЛЖИ возврата ReadFile и возврат GetLastError ERROR_HANDLE_EOF.
Если EOF обнаружен в течение последующей асинхронной операции, вызов на GetOverlappedResult, чтобы получать результаты этой операции ЛЖИ возврата и возврата GetLastError ERROR_HANDLE_EOF.

Для того, чтобы отменять все незаконченные асинхронные операции В/В, используйте функцию CancelIO. Эта функция только отменяет операции выпущенные разговором резьбы для определенной файловой ручки. ОПЕРАЦИИ В/В, которые отменены кончать с ошибкой ERROR_OPERATION_ABORTED.
Следующий код образца иллюстрируется тестируясь для конца--файла для асинхронной операции чтения:

// установленное перекрывшее структурные области //, чтобы упрощать этот образец, мы посторонимся gOverLapped ручки события.Смещение = 0;
gOverLapped.OffsetHigh = 0;
gOverLapped.hEvent = НЕДЕЙСТВИТЕЛЬНЫЙ;

// попытка асинхронная операция чтения bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, &gOverlapped);

// если была проблема, или async. действие все еще рассматривающийся...
если (!bResult)
{
// сделка с кодовым ключом ошибки (dwError = GetLastError())

{
случай ERROR_HANDLE_EOF:
{
// мы достигнуты конец файла // в течение вызова на ReadFile

// код, чтобы оперировать это
}

случай ERROR_IO_PENDING:
{
// асинхронный в/в - все еще в процессе развития

// сделайте нечто другое на некоторое время GoDoSomethingElse();

// чек в результатах асинхронного чтения bResult = GetOverlappedResult(hFile, &gOverlapped,

&nBytesRead, FALSE);

// если была проблема...
если (!bResult)
{
// сделка с кодовым ключом ошибки (dwError = GetLastError())
{
случай ERROR_HANDLE_EOF:
{
// мы достигнуты конец файла //в течение асинхронной операции
}

// сделка с другими случаями ошибки

}
}
} // конечный случай

// сделка с другими случаями ошибки

} // конец переключать } // конец если


Смотри Также

CancelIo, CreateFile, GetCommTimeouts, GetOverlappedResult, GetQueuedCompletionStatus, ПЕРЕКРЫТОЕ, PeekNamedPipe, ReadFileEx, SetCommTimeouts, WriteFile


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz