OpenFile function (winbase.h)
Creates, opens, reopens, or deletes a file.
Syntax
Parameters
The name of the file.
The string must consist of characters from the 8-bit Windows character set. The OpenFile function does not support Unicode file names or opening named pipes.
A pointer to the OFSTRUCT structure that receives information about a file when it is first opened.
The structure can be used in subsequent calls to the OpenFile function to see an open file.
The OFSTRUCT structure contains a path string member with a length that is limited to OFS_MAXPATHNAME characters, which is 128 characters. Because of this, you cannot use the OpenFile function to open a file with a path length that exceeds 128 characters. The CreateFile function does not have this path length limitation.
The action to be taken.
This parameter can be one or more of the following values.
Value | Meaning |
---|---|
OF_CANCEL 0x00000800 | Ignored. To produce a dialog box containing a Cancel button, use OF_PROMPT. |
OF_CREATE 0x00001000 | Creates a new file. If the file exists, it is truncated to zero (0) length. |
OF_DELETE 0x00000200 | Deletes a file. |
OF_EXIST 0x00004000 | Opens a file and then closes it. Use this to test for the existence of a file. |
OF_PARSE 0x00000100 | Fills the OFSTRUCT structure, but does not do anything else. |
OF_PROMPT 0x00002000 | Displays a dialog box if a requested file does not exist. A dialog box informs a user that the system cannot find a file, and it contains Retry and Cancel buttons. The Cancel button directs OpenFile to return a file-not-found error message. |
OF_READ 0x00000000 | Opens a file for reading only. |
OF_READWRITE 0x00000002 | Opens a file with read/write permissions. |
OF_REOPEN 0x00008000 | Opens a file by using information in the reopen buffer. |
OF_SHARE_COMPAT 0x00000000 | For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a specified computer to open the file any number of times. Other efforts to open a file with other sharing modes fail. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. |
OF_SHARE_DENY_NONE 0x00000040 | Opens a file without denying read or write access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode by any other process, the function fails. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. |
OF_SHARE_DENY_READ 0x00000030 | Opens a file and denies read access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode, or for read access by any other process, the function fails. This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function. |
OF_SHARE_DENY_WRITE 0x00000020 | Opens a file and denies write access to other processes. On MS-DOS-based file systems, if a file has been opened in compatibility mode, or for write access by any other process, the function fails. This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function. |
OF_SHARE_EXCLUSIVE 0x00000010 | Opens a file with exclusive mode, and denies both read/write access to other processes. If a file has been opened in any other mode for read/write access, even by the current process, the function fails. |
OF_VERIFY | Verifies that the date and time of a file are the same as when it was opened previously. This is useful as an extra check for read-only files. |
OF_WRITE 0x00000001 | Opens a file for write access only. |
Return value
If the function succeeds, the return value specifies a file handle to use when performing file I/O. To close the file, call the CloseHandle function using this 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 file name and extension only, this function searches for a matching file in the following directories and the order shown:
- The directory where an application is loaded.
- The current directory.
- The Windows system directory.
Use the GetSystemDirectory function to get the path of this directory.
The 16-bit Windows system directory.
There is not a function that retrieves the path of this directory, but it is searched.
The Windows directory.
Use the GetWindowsDirectory function to get the path of this directory.
The lpFileName parameter cannot contain wildcard characters.
The OpenFile function does not support the OF_SEARCH flag that the 16-bit Windows OpenFile function supports. The OF_SEARCH flag directs the system to search for a matching file even when a file name includes a full path. Use the SearchPath function to search for a file.
A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote machine when the value of the uStyle parameter is the OF_DELETE access flag OR’ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE share access. To avoid the sharing violation in this scenario, open the remote file or directory with OF_DELETE access only, or call DeleteFile without first opening the file or directory for deletion.
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 |
В
CsvFs will do redirected IO for compressed files.
вызывает call
Вызывает одну пакетную программу из другой без остановки родительской пакетной программы. Calls one batch program from another without stopping the parent batch program. Команда Call принимает метки в качестве целевого объекта вызова The call command accepts labels as the target of the call
Вызов не оказывает влияния на командную строку, если она используется вне скрипта или пакетного файла. Call has no effect at the command prompt when it is used outside of a script or batch file.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
[ :][ |
]
Параметры пакета Batch parameters
Ссылки на аргумент скрипта пакетной службы (%0, %1. ) перечислены в следующих таблицах. The batch script argument references (%0, %1, . ) are listed in the following tables.
Использование значения % * в пакетном скрипте означает все аргументы (например, %1, %2, %3. ). Using the %* value in a batch script refers to all the arguments (for example, %1, %2, %3. ).
Можно использовать следующие необязательные синтаксисы в качестве подстановок для пакетных параметров (% n): You can use the following optional syntaxes as substitutions for batch parameters (%n):
Параметр Batch Batch Parameter | Описание Description |
---|---|
% 1 | Развертывает %1 и удаляет окружающие кавычки. Expands %1 and removes surrounding quotation marks. |
% f1 | Расширение %1 до полного пути. Expands %1 to a fully qualified path. |
% d1 | Расширение %1 до буквы диска. Expands %1 to a drive letter only. |
% p1 | Развертывает %1 только для пути. Expands %1 to a path only. |
% n1 | Расширение %1 только на имя файла. Expands %1 to a file name only. |
% x1 | Развертывает %1 только для расширения имени файла. Expands %1 to a file name extension only. |
% s1 | Расширение %1 до полного пути, содержащего только короткие имена. Expands %1 to a fully qualified path that contains short names only. |
% a1 | Развертывает %1 для атрибутов файла. Expands %1 to the file attributes. |
% t1 | Увеличивает %1 до даты и времени файла. Expands %1 to the date and time of file. |
% z1 | Расширение %1 до размера файла. Expands %1 to the size of the file. |
% $PATH:1 | Выполняет поиск в каталогах, перечисленных в переменной среды PATH, и разворачивает %1 до полного имени найденного первого каталога. Searches the directories listed in the PATH environment variable, and expands %1 to the fully qualified name of the first directory found. Если имя переменной среды не определено или файл не найден при поиске, то этот модификатор разворачивается до пустой строки. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string. |
В следующей таблице показано, как можно объединить модификаторы с пакетными параметрами для составных результатов. The following table shows how you can combine modifiers with the batch parameters for compound results:
Параметр Batch с модификатором Batch Parameter with Modifier | Описание Description |
---|---|
% dp1 | Расширение %1 до буквы диска и пути. Expands %1 to a drive letter and path only. |
% nx1 | Развертывает %1 только для имени файла и расширения. Expands %1 to a file name and extension only. |
% точка DP $ PATH: 1 % dp$PATH:1 | Выполняет поиск в каталогах, перечисленных в переменной среды PATH для %1, а затем разворачивается на букву диска и путь к первому найденному каталогу. Searches the directories listed in the PATH environment variable for %1, and then expands to the drive letter and path of the first directory found. |
% ftza1 | Разворачивает %1 для вывода выходных данных, аналогичных команде dir . Expands %1 to display output similar to the dir command. |
В приведенных выше примерах %1 и Path могут быть заменены другими допустимыми значениями. In the above examples, %1 and PATH can be replaced by other valid values. %
Синтаксис завершается допустимым номером аргумента. The %
syntax is terminated by a valid argument number. %
Модификаторы нельзя использовать с % *. The %
modifiers cannot be used with %*.
Комментарии Remarks
Использование параметров пакетной службы: Using batch parameters:
Пакетные параметры могут содержать любые сведения, которые можно передать в пакетную программу, включая параметры командной строки, имена файлов, параметры пакета %0 – %9 и переменные (например, % бод%). Batch parameters can contain any information that you can pass to a batch program, including command-line options, file names, the batch parameters %0 through %9, and variables (for example, %baud%).
С помощью параметра: Using the parameter:
Используя вызов с параметром, вы создаете новый контекст файла пакета и передаете управление оператору после указанной метки. By using call with the parameter, you create a new batch file context and pass control to the statement after the specified label. При первом обнаружении конца пакетного файла (то есть после перехода к метке) управление возвращается оператору после оператора Call . The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement. При втором обнаружении конца пакетного файла пакетный сценарий завершается. The second time the end of the batch file is encountered, the batch script is exited.
Использование каналов и символов перенаправления: Using pipes and redirection symbols:
Не используйте каналы (|) или символы перенаправления ( или > ) с вызовом. Do not use pipes (|) or redirection symbols ( or > ) with call.
Выполнение рекурсивного вызова Making a recursive call
Можно создать пакетную программу, которая вызывает саму себя. You can create a batch program that calls itself. Однако необходимо указать условие выхода. However, you must provide an exit condition. В противном случае родительские и дочерние пакетные программы могут подбираться бесконечно. Otherwise, the parent and child batch programs can loop endlessly.
Работа с расширениями команд Working with command extensions
Если расширения команд включены, вызов принимает в качестве цели вызова. If command extensions are enabled, call accepts as the target of the call. Правильный синтаксис: call : The correct syntax is call :