На главную

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 | Скачать Вниз

WriteFileEx



The WriteFileEx function writes data to a file. It is designed solely for asynchronous operation, unlike WriteFile, which is designed for both synchronous and asynchronous operation.

WriteFileEx reports its completion status asynchronously, calling a specified completion routine when writing is completed and the calling thread is in an alertable wait state.

BOOL WriteFileEx(

HANDLE hFile, // handle to output file
LPCVOID lpBuffer, // pointer to input buffer
DWORD nNumberOfBytesToWrite, // number of bytes to write
LPOVERLAPPED lpOverlapped, // pointer to async. i/o data
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // ptr. to completion routine
);


Parameters

hFile

An open handle that specifies the file entity to be written to. This file handle must have been created with the FILE_FLAG_OVERLAPPED flag and with GENERIC_WRITE access to the file.

Windows NT: 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: 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 operations on disk files.

lpBuffer

Points to the buffer containing the data to be written to the file.

This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

nNumberOfBytesToWrite

Specifies the number of bytes to write to the file.

If nNumberOfBtyesToWrite is zero, this function does nothing; in particular, it does not truncate the file. For additional discussion, see the following Remarks section.

lpOverlapped

Points to an OVERLAPPED data structure that supplies data to be used during the overlapped (asynchronous) write operation.

For files that support byte offsets, you must specify a byte offset at which to start writing to the file. You specify this offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files that do not support byte offsets ѕ named pipes, for example ѕ you must set Offset and OffsetHigh to zero, or WriteFileEx fails.
The WriteFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a WriteFileEx call. WriteFileEx signals completion of its writing operation by calling, or queueing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The WriteFileEx function does use the Internal and InternalHigh members of the OVERLAPPED structure. You should not change the value of these members.
The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that can go out of scope while the write operation is pending completion.

lpCompletionRoutine

Points to a completion routine to be called when the write operation has been completed and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
If the WriteFileEx function succeeds, the calling thread has an asynchronous I/O (input/output) operation pending: the overlapped write operation to the file. When this I/O operation finishes, and the calling thread is blocked in an alertable wait state, the operating system calls the function pointed to by lpCompletionRoutine, and the wait completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds and the file-writing operation finishes, but the calling thread is not in an alertable wait state, the system queues the call to *
lpCompletionRoutine, holding the call until the calling thread enters an alertable wait state. See Synchronization for more information about alertable wait states and overlapped input/output operations.

Remarks

If part of the output file is locked by another process, and the specified write operation overlaps the locked portion, the WriteFileEx function fails.
Applications must not read from nor write to the output buffer that a write operation is using until the write operation completes. Premature access of the output buffer may lead to corruption of the data written from that buffer.
The WriteFileEx function may fail, returning the messages ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY if there are too many outstanding asynchronous I/O requests.

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.
If hFile is a handle to a named pipe, or other file entity that doesn't support byte offsets, the Offset and OffsetHigh members of the OVERLAPPED structure pointed to by lpOverlapped must be zero, or the WriteFileEx function fails.

An application uses the WaitForSingleObjectEx, WaitForMultipleObjectsEx, MsgWaitForMultipleObjectsEx, SignalObjectAndWait, and SleepEx functions to enter an alertable wait state. Refer to Synchronization for more information about alertable wait states and overlapped input/output operations.
Windows 95: On this platform, neither WriteFileEx nor ReadFileEx can be used by the comm ports to communicate. However, you can use WriteFile and ReadFile to perform asynchronous communication.

See Also

CancelIo, CreateFile, FileIOCompletionRoutine, MsgWaitForMultipleObjectsEx, OVERLAPPED, ReadFileEx, SetEndOfFile, SleepEx, SignalObjectAndWait, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFile




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

WriteFileEx



Функция WriteFileEx записывает данные в файл. Разработано исключительно для асинхронной операции, в отличие от WriteFile, которая разработана для как синхронной так и асинхронной операции.

WriteFileEx СООБЩАЕТ свой статус завершения асинхронно, вызывающий определенную программу завершения когда запись завершена и вызывающая резьба - в состоянии ожидания alertable.

BOOL WriteFileEx(

РУЧКА hFile, // оперируется в выходной файл LPCVOID lpBuffer, // указатель, чтобы вводить буфер DWORD nNumberOfBytesToWrite, // количество байтов, чтобы записывать LPOVERLAPPED lpOverlapped, // указатель в в/в данные async. LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // ptr. в программу завершения
);


Параметры

hFile

Открытая ручка, которая определяет файловый объект, который нужно записывать, чтобы. Эта файловая ручка по-видимому создана флагом FILE_FLAG_OVERLAPPED и с доступом GENERIC_WRITE к файлу.

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

lpBuffer

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

Этот буфер должен остаться в силе в течение записывать операции. Вызывающий оператор не должен использовать этот буфер пока записывать операция не будет завершена.

nNumberOfBytesToWrite

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

Если nNumberOfBtyesToWrite - нуль, эта функция делает ничто; в конкретном, это не исключает файл. Для дополнительной дискуссии, смотри секцию Замечаний следующего.

lpOverlapped

Точки на ПЕРЕКРЫТУЮ структуру данных, которые поставляют данные, которые нужно использоваться в течение перекрытой записи (асинхронный) операция.

Для файлов, которые поддерживают байтовые смещения, Вы должны определить байтовое смещение в котором, чтобы начинать писаться в файл. Вы определяете это смещение устанавливая Смещение и участников OffsetHigh ПЕРЕКРЫТОЙ структуры. Для файлов, что не поддерживать байтовые смещения U назвавшее трубы, например U Вы должны установить Смещение и OffsetHigh в нуль, или WriteFileEx терпит неудачу.
Функция WriteFileEx игнорирует ПЕРЕКРЫТЫЙ структурный элемент hEvent. Приложение свободно, чтобы использовать этот элемент для своих собственных целей в контексте вызова WriteFileEx. WriteFileEx СИГНАЛИЗИРУЕТ завершение своей операции записи вызывая, или ставя в очередь вызов на, программа завершения указывалась, чтобы lpCompletionRoutine, так что ему не нужно ручка события.

Функция WriteFileEx использует Внутренних и участников InternalHigh ПЕРЕКРЫТОЙ структуры. Вам не следует изменить величину этих участников.
ПЕРЕКРЫТАЯ структура данных должна остаться в силе в течение записывать операции. Это не должно быть переменной, которая может выходить из области тогда как записывать операция рассматривает завершение.

lpCompletionRoutine

Точки на программу завершения, которые нужно быть названы когда записывать операция завершена и вызывающая резьба - в состоянии ожидания alertable. Более подробно об этой программе завершения, смотри FileIOCompletionRoutine.



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

Если функция добивается успеха, обратная величина ненулевая.
Если функция терпит неудачу, обратная величина нулевая. Для того, чтобы расширять информацию ошибки, назовите GetLastError.
Если функция WriteFileEx добивается успеха, вызывающая резьба имеет асинхронную В/В операцию (ввод/выход) рассматривать: перекрытая записывать операция в файл. Когда эта операция В/В завершается, и вызывающая резьба заблокирована в состоянии ожидания alertable, операционная система называет функцию указанную, чтобы lpCompletionRoutine, и ожидание завершается с обратным кодом WAIT_IO_COMPLETION.

Если функция добивается успеха и операция файловой записи завершается, но вызывающая резьба - не в состоянии ожидания alertable, система ставит в очередь вызов, чтобы * lpCompletionRoutine, удерживающий вызов пока вызов резьбы не введет состояние ожидания alertable. Смотри Синхронизацию более подробно о alertable состояниях ожидания и перекрытого ввода/выходные операции.

Замечания

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

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

Приложение использует WaitForSingleObjectEx, WaitForMultipleObjectsEx, MsgWaitForMultipleObjectsEx, SignalObjectAndWait, и функции SleepEx, чтобы вводить состояние ожидания alertable. Посмотрите Синхронизацию более подробно о alertable состояниях ожидания и перекрытого ввода/выходные операции.
Windows 95: На этой платформе, ни WriteFileEx ни ReadFileEx может быть использован портами comm, чтобы связываться. Тем не менее, Вы можете использовать WriteFile и ReadFile, чтобы выполнять асинхронную связь.

Смотри Также

CancelIo, CreateFile, FileIOCompletionRoutine, MsgWaitForMultipleObjectsEx, ПЕРЕКРЫТОЕ, ReadFileEx, SetEndOfFile, SleepEx, SignalObjectAndWait, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFile




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