Windows check file exists

How to verify if a file exists in a batch file?

I have to create a .BAT file that does this:

  1. If C:\myprogram\sync\data.handler exists, exit;
  2. If C:\myprogram\html\data.sql does not exist, exit;
  3. In C:\myprogram\sync\ delete all files and folders except ( test , test3 and test2 )
  4. Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
  5. Call other batch file with option sync.bat myprogram.ini .

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

3 Answers 3

You can use IF EXIST to check for a file:

If you do not need an «else», you can do something like this:

Here’s a working example of searching for a file or a folder:

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

Here is a good example on how to do a command if a file does or does not exist:

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

Use the XCOPY command:

I will explain what the /c /d /h /e /i /y means:

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

How do I check whether a file exists in C++ for a Windows program?

This is for a Windows-only program so portable code is not an issue.

12 Answers 12

There are two common ways to do this in Windows code. GetFileAttributes, and CreateFile,

Читайте также:  Linux во что поиграть 2021

This will tell you a file exists, but but it won’t tell you whether you have access to it. for that you need to use CreateFile.

But remember, that even if you get back true from one of these calls, the file could still not exist by the time you get around to opening it. Many times it’s best to just behave as if the file exists and gracefully handle the errors when it doesn’t.

According to the venerable Raymond Chen, you should use GetFileAttributes if you’re superstitious.

Use _access or stat .

This is a bit more of a complex question. There is no 100% way to check for existence of a file. All you can check is really «exstistence of a file that I have some measure of access to.» With a non-super user account, it’s very possible for a file to exist that you have no access to in such a way that access checks will not reveal the existincae of an file.

For instance. It’s possible to not have access to a particular directory. There is no way then to determine the existence of a file within that directory.

That being said, if you want to check for the existence of a file you have a measure of access to use one of the following: _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64

GetFileAttributes is what you’re looking for. If it returns a value that is not INVALID_FILE_ATTRIBUTES the file exists.

Open it. You can’t reliably test if a file exists on a multi-tasking operating system. When you open it you can make sure it doesn’t disappear.

C++: Which is the best method of checking for file existence on windows platform [duplicate]

Which is the best method for checking for file existence:

Also if you think option 1 is the better method, can you tell me how to define 0xffffffff as a constant (I don’t want to use #define)

11 Answers 11

Note that GetFileAttributes() may fail for other reasons than lack of existence (for example permissions issues). I would add a check on the error code for robustness:

There are two things to consider here:

Checking if the file exists via its attributes is potentially many orders of magnitude faster — If a file exists on a ‘slow’ file system — tape, network storage, cd etc then opening the file will involve an actual round trip to the files location. The files attributes on the other hand are queried and cached by the filesystem drivers when the directory is queried, so probing file attributes involves a once off directory enumeration cost — meaning far fewer round trips — which can be a significant saving if multiple «slow» files are being checked.

Читайте также:  Как включить автозапуск дисковода windows 10

However, the files attributes merely indicate that the file existed at the time the call was made. The file can be deleted, or you might not haver permissions to access it. If you are about to try and open the file anyway, it would be better to dispense with the file attributes check and actually try and open the file.

If you’re targeting only Windows, option #1 is clearly the better of the two. Also, the constant you’re looking for already exists in the Windows headers — it’s called INVALID_FILE_ATTRIBUTES .

How can we check if a file Exists or not using Win32 program?

How can we check if a file Exists or not using a Win32 program? I am working for a Windows Mobile App.

8 Answers 8

Here is a sample I just knocked up:

Use GetFileAttributes to check that the file system object exists and that it is not a directory.

You can make use of the function GetFileAttributes . It returns 0xFFFFFFFF if the file does not exist.

How about simply:

But I’d probably go with GetFileAttributes .

You can try to open the file. If it failed, it means not exist in most time.

Came across the same issue and found this brief code in another forum which uses GetFileAttributes Approach

where szPath is the file-path.

Another more generic non-windows way:

Not the answer you’re looking for? Browse other questions tagged windows winapi file or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

File. Exists(String) Метод

Определение

Определяет, существует ли заданный файл. Determines whether the specified file exists.

Параметры

Проверяемый файл. The file to check.

Возвращаемое значение

Значение true , если вызывающий оператор имеет требуемые разрешения и path содержит имя существующего файла; в противном случае — false . true if the caller has the required permissions and path contains the name of an existing file; otherwise, false . Этот метод также возвращает false , если path — null , недействительный путь или строка нулевой длины. This method also returns false if path is null , an invalid path, or a zero-length string. Если у вызывающего оператора нет достаточных полномочий на чтение заданного файла, исключения не создаются, а данный метод возвращает false вне зависимости от существования path . If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path .

Читайте также:  Error 1719 windows installer service что это

Примеры

В следующем примере определяется, существует ли файл. The following example determines if a file exists.

Комментарии

ExistsМетод не должен использоваться для проверки пути. Этот метод просто проверяет, существует ли файл, указанный в path Exists. The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Передача недопустимого пути для Exists возврата false . Passing an invalid path to Exists returns false . Чтобы проверить, содержит ли путь недопустимые символы, можно вызвать GetInvalidPathChars метод, чтобы получить символы, недопустимые для файловой системы. To check whether the path contains any invalid characters, you can call the GetInvalidPathChars method to retrieve the characters that are invalid for the file system. Можно также создать регулярное выражение для проверки того, является ли путь допустимым для вашей среды. You can also create a regular expression to test the whether the path is valid for your environment. Примеры допустимых путей см. в разделе File . For examples of acceptable paths, see File.

Чтобы проверить, существует ли каталог, см Directory.Exists . раздел. To check if a directory exists, see Directory.Exists.

Имейте в виду, что другой процесс потенциально может сделать что-то с файлом в промежутке между вызовом Exists метода и выполнением другой операции с файлом, например Delete . Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.

path Параметр может указывать сведения относительного или абсолютного пути. The path parameter is permitted to specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.

Если path описывает каталог, этот метод возвращает false . If path describes a directory, this method returns false . Конечные пробелы удаляются из path параметра перед определением наличия файла. Trailing spaces are removed from the path parameter before determining if the file exists.

Метод возвращает значение, если возникла Exists false Ошибка при попытке определить, существует ли указанный файл. The Exists method returns false if any error occurs while trying to determine if the specified file exists. Это может произойти в ситуациях, когда вызываются такие исключения, как передача имени файла с недопустимыми символами или слишком много символов, неудачный или отсутствующий диск или если вызывающий объект не имеет разрешения на чтение файла. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Оцените статью