На главную

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

OpenFile



The OpenFile function creates, opens, reopens, or deletes a file.

This function is provided for compatibility with 16-bit versions of Windows. In particular, the OpenFile function cannot open a named pipe. Win32-based applications should use the CreateFile function.

HFILE OpenFile(

LPCSTR lpFileName, // pointer to filename
LPOFSTRUCT lpReOpenBuff, // pointer to buffer for file information
UINT uStyle // action and attributes
);


Parameters

lpFileName

Points to a null-terminated string that names the file to be opened. The string must consist of characters from the Windows 3.x character set. The OpenFile function does not support Unicode filenames.

lpReOpenBuff

Points to the OFSTRUCT structure that receives information about the file when it is first opened. The structure can be used in subsequent calls to the OpenFile function to refer to the open file.
The OFSTRUCT structure contains a pathname string member whose length is limited to OFS_MAXPATHNAME characters. OFS_MAXPATHNAME is currently defined to be 128. Because of this, you cannot use the OpenFile function to open a file whose path length exceeds 128 characters. The CreateFile function does not have such a path length limitation.

uStyle

Specifies the action to take. The following values can be combined by using the bitwise OR operator:

Value Meaning
OF_CANCEL Ignored. In the Win32 application programming interface (API), the OF_PROMPT style produces a dialog box containing a Cancel button.
OF_CREATE Creates a new file. If the file already exists, it is truncated to zero length.
OF_DELETE Deletes the file.
OF_EXIST Opens the file and then closes it. Used to test for a file's existence.
OF_PARSE Fills the OFSTRUCT structure but carries out no other action.
OF_PROMPT Displays a dialog box if the requested file does not exist. The dialog box informs the user that Windows cannot find the file, and it contains Retry and Cancel buttons. Choosing the Cancel button directs OpenFile to return a file-not-found error message.
OF_READ Opens the file for reading only.
OF_READWRITE Opens the file for reading and writing.
OF_REOPEN Opens the file using information in the reopen buffer.
OF_SHARE_COMPAT For MS-DOS-based file systems using the Win32 API, opens the file with compatibility mode, allowing any process on a specified computer to open the file any number of times. Other efforts to open with any other sharing mode fail. Windows NT: This flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_NONE Opens the file without denying read or write access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode by any other process, the function fails. Windows NT: This flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_READ Opens the file and denies read access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode or for read access by any other process, the function fails. Windows NT: This flag is mapped to the CreateFile function's FILE_SHARE_WRITE flag.
OF_SHARE_DENY_WRITE Opens the file and denies write access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode or for write access by any other process, the function fails. Windows NT: This flag is mapped to the CreateFile function's FILE_SHARE_READ flag.
OF_SHARE_EXCLUSIVE Opens the file with exclusive mode, denying both read and write access to other processes. If the file has been opened in any other mode for read or write access, even by the current process, the function fails.
OF_VERIFY Verifies that the date and time of the file are the same as when it was previously opened. This is useful as an extra check for read-only files.
OF_WRITE Opens the file for writing only.


Return Values

If the function succeeds, the return value specifies a file handle.
If the function fails, the return value is HFILE_ERROR. To get extended error information, call GetLastError.

Remarks

If the lpFileName parameter specifies a filename and extension only, this function searches for a matching file in the following directories, in the order shown:

1. The directory from which the application loaded.
2. The current directory.
3. Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4. Windows NT: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.
5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
6. The directories that are listed in the PATH environment variable.



The lpFileName parameter cannot contain wildcard characters.
The Win32 OpenFile function does not support the OF_SEARCH flag supported by the 16-bit Windows OpenFile function. The OF_SEARCH flag directs Windows to search for a matching file even when the filename includes a full path. To search for a file in a Win32-based application, use the SearchPath function.
To close the file after use, call the _lclose function.

See Also

CreateFile, GetSystemDirectory, GetWindowsDirectory, _lclose, OFSTRUCT, SearchPath


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

OpenFile



Функция OpenFile создает, открывает, открывает вновь, или удаляет файл.

Эта функция предусмотрена для совместимости 16- битовыми версиями Окна. В конкретном, функция OpenFile не может открыть поименованную трубу. базирующиеся приложения Win32 должны использовать функцию CreateFile.

HFILE OpenFile(

LPCSTR lpFileName, // УКАЗАТЕЛЬ на filename LPOFSTRUCT lpReOpenBuff, // указатель, чтобы буферизоваться для файлового действия информации UINT uStyle // и атрибуты
);


Параметры

lpFileName

Точки на недействительный расторгнутую строку, которые называют файл, который нужно открываться. Строка должна состоять из символов из 3.x набора символов Windows. Функция OpenFile не поддерживает Уникод filenames.

lpReOpenBuff

Точки на структуру OFSTRUCT, которые получают информацию о файле когда это сначала открыто. Структура может быть использована на последующих вызовах в функцию OpenFile, чтобы ссылаться на открытый файл.
Структура OFSTRUCT содержит элемент строки pathname, чья длина ограниченная символами OFS_MAXPATHNAME. OFS_MAXPATHNAME к настоящему времени определен, чтобы быть 128. Из-за этого, Вы не можете использовать функцию OpenFile, чтобы открывать файл, чья длина пути превышает 128 символов. Функция CreateFile нет имеет такое ограничение длины пути.

uStyle

Определяет действие, чтобы требоваться. Следующее величин может быть объединено использованием поразрядный ИЛИ оператор:

Значение Величины
OF_CANCEL Проигнорирован. В приложении Win32, программирующем интерфейс (API), стиль OF_PROMPT производит диалогового блока, содержащего кнопку Отмены.
OF_CREATE Создает новый файл. Если файл уже существует, он исключен на нулевую длину.
OF_DELETE Удаляет файл.
OF_EXIST Открывает файл затем закрывает это. Использованное, чтобы тестироваться для файлового существования.
OF_PARSE Заполняет структуру OFSTRUCT но не выполняет никакое другое действие.
OF_PROMPT Отображает диалогового блока если запрошенный файл не существует. Диалоговый блок сообщает пользователя, что Windows не может найти файл, и это содержит Повторную попытку и Отменяет кнопки. Выбирая кнопку Отмены прямое OpenFile, чтобы возвращать файл-не-обнаруживший сообщение ошибки.
OF_READ Открывает файл для чтения только.
OF_READWRITE Открывает файлу для чтения и записи.
OF_REOPEN Открывает файл, использовавший информацию в открывать вновь буфер.
OF_SHARE_COMPAT Для МС-основывал файловые системы DOS, использовавшие Win32 API, открывал файл с режимом совместимости, допуская любой процесс в определенном компьютере, чтобы открывать файл любое раз (а). Другие меры, чтобы открываться с любым другим разделением режима терпеть неудачу. Windows NT: Этот флаг отображен на CreateFile функциональный FILE_SHARE_READ | флаги FILE_SHARE_WRITE.
OF_SHARE_DENY_NONE Открывает файл не запреща прочитанное или доступ записи к другим процессам. На МС-основавшее файловые системы DOS, использовавшие Win32 API, если файл открыт в режиме совместимости любым другим процессом, функция терпит неудачу. Windows NT: Этот флаг отображен на CreateFile функциональный FILE_SHARE_READ | флаги FILE_SHARE_WRITE.
OF_SHARE_DENY_READ Открывает файл и запрещит прочитанный доступ к другим процессам. На МС-основавшее файловые системы DOS, использовавшие Win32 API, если файл открыт в режиме совместимости или для доступа чтения любым другим процессом, функция терпит неудачу. Windows NT: Этот флаг отображен на CreateFile функционального флага FILE_SHARE_WRITE.
OF_SHARE_DENY_WRITE Открывает файл и запрещит записывать доступ к другим процессам. На МС-основавшее файловые системы DOS, использовавшие Win32 API, если файл открыт в режиме совместимости или для записывать доступа любым другим процессом, функция терпит неудачу. Windows NT: Этот флаг отображен на CreateFile функционального флага FILE_SHARE_READ.
OF_SHARE_EXCLUSIVE Открывает файл с исключительный режим, запрещащий как прочитанное так и доступ записи к другим процессам. Если файл открыт в любом другом режиме для чтения или доступа записи, даже текущим процессом, функция терпит неудачу.
OF_VERIFY Проверяет, что дата и время файла такие же как и когда прежде было открыто. Это полезное как дополнительный чек только для чтения файлов.
OF_WRITE Открывает файл для записи только.


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

Если функция добивается успеха, обратная величина определяет файловую ручку.
Если функция терпит неудачу, обратная величина - HFILE_ERROR. Для того, чтобы расширять информацию ошибки, вызовите GetLastError.

Замечания

Если параметр lpFileName определяет filename и расширение только, эта функция ищет сочетающийся файл в следующих директориях, в порядке показанном:

1. Директорий из которого приложение загружалось.
2. Текущий директорий.
3. Windows 95: системный директорий Windows. Используйте функцию GetSystemDirectory, чтобы получать путь этого директория.

Windows NT: системный директорий 32- бита Windows. Используйте функцию GetSystemDirectory, чтобы получать путь этого директория. Имя этого директория - SYSTEM32.

4. Windows NT: системный директорий 16- бита Windows. Нет функции Win32, что получает путь этого директория, но поискано. Имя этого директория СИСТЕМНОЕ.
5. Директорий Windows. Используйте функцию GetWindowsDirectory, чтобы получать путь этого директория.
6. Директории, которые указаны в переменной среды ПУТИ.



Параметр lpFileName не может содержать символы шаблона.
Функция Win32 OpenFile не поддерживает флаг OF_SEARCH поддерживанный 16- битовой функцией Windows OpenFile. Флаг OF_SEARCH направляет Windows, чтобы искать сочетающийся файл даже когда filename включает полный путь. Для того, чтобы искать файл в базирующемся приложении Win32, используйте функцию SearchPath.
Для того, чтобы закрывать файл после использования, вызовите _lclose функция.

Смотри Также

CreateFile, GetSystemDirectory, GetWindowsDirectory, _lclose, OFSTRUCT, SearchPath


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