Windows file exist check

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 .

Примеры

В следующем примере определяется, существует ли файл. 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.

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,

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.

Читайте также:  Ваш диск истории файлов был слишком долго отключен windows 10

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.

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.

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:

Fastest way to check if a file exist using standard C++/C++11/C?

I would like to find the fastest way to check if a file exist in standard C++11, C++, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of /* SOMETHING */ in the following function?

Читайте также:  Mac os xeon x5450

20 Answers 20

Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn’t.

Results for total time to run the 100,000 calls averaged over 5 runs,

Method Time
exists_test0 (ifstream) 0.485s
exists_test1 (FILE fopen) 0.302s
exists_test2 (posix access()) 0.202s
exists_test3 (posix stat()) 0.134s

The stat() function provided the best performance on my system (Linux, compiled with g++ ), with a standard fopen call being your best bet if you for some reason refuse to use POSIX functions.

Remark : in C++14 and as soon as the filesystem TS will be finished and adopted, the solution will be to use:

and since C++17, only:

I use this piece of code, it works OK with me so far. This does not use many fancy features of C++:

For those who like boost:

or, since ISO C++17:

It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system . if you’re writing ANSI C, the fastest way is fopen because it’s the only way (a file might exist but not be openable, but you probably really want openable if you need to «do something on it»). C++, POSIX, Windows all offer additional options.

While I’m at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution . a case of the XY problem. You also say «in standard c++11(or)c++(or)c» . which are all different, and this also is inconsistent with your requirement for speed . the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.

Without using other libraries, I like to use the following code snippet:

This works cross-platform for Windows and POSIX-compliant systems.

Same as suggested by PherricOxide but in C

Another 3 options under windows:

You may also do bool b = std::ifstream(‘filename’).good(); . Without the branch instructions(like if) it must perform faster as it needs to be called thousands of times.

If you need to distinguish between a file and a directory, consider the following which both use stat which the fastest standard tool as demonstrated by PherricOxide:

You can use std::ifstream , funcion like is_open , fail , for example as below code (the cout «open» means file exist or not):

cited from this answer

I need a fast function that can check if a file is exist or not and PherricOxide’s answer is almost what I need except it does not compare the performance of boost::filesystem::exists and open functions. From the benchmark results we can easily see that :

Using stat function is the fastest way to check if a file is exist. Note that my results are consistent with that of PherricOxide’s answer.

The performance of boost::filesystem::exists function is very close to that of stat function and it is also portable. I would recommend this solution if boost libraries is accessible from your code.

Benchmark results obtained with Linux kernel 4.17.0 and gcc-7.3:

Below is my benchmark code:

where R is your sequence of path-like things, and exists() is from the future std or current boost. If you roll your own, keep it simple,

The branched solution isn’t absolutely terrible and it won’t gobble file descriptors,

Using MFC it is possible with the following

Where FileName is a string representing the file you are checking for existance

there is only one faster way to check if the file exists and if you have permission to read it the way is using C language wish is faster and can be used also in any version in C++

solution: in C there is a library errno.h which has an external (global) integer variable called errno which contains a number that can be used to recognize the type of error

Here is a simple example!

All of the other answers focus on individually checking every file, but if the files are all in one directory (folder), it might be much more efficient to just read the directory and check for the existence of every file name you want.

This might even be more efficient even if the files are spread across several directories, depends on the exact ratio of directories to files. Once you start getting closer to each target file being in its own directory, or there being lots of other files in the same directories which you don’t want to check for, then I’d expect it to finally tip over into being less efficient than checking each file individually.

A good heuristic: working on a bunch of data you already have is much faster than asking the operating system for any amount of data. System call overhead is huge relative to individual machine instructions. So it is almost always going to be faster to ask the OS «give me the entire list of files in this directory» and then to dig through that list, and slower to ask the OS «give me information on this file», «okay now give me information on this other file», «now give me information on . «, and so on.

Every good C library implements its «iterate over all files in a directory» APIs in an efficient way, just like buffered I/O — internally it reads up a big list of directory entries from the OS at once, even though the APIs look like asking the OS for each entry individually.

So if I had this requirement, I would

  1. do everything possible to encourage the design and usage so that all the files were in one folder, and no other files were in that folder,
  2. put the list of file names that I need to be present into a data structure in memory that has O(1) or at least O(log(n)) lookup and delete times (like a hash map or a binary tree),
  3. list the files in that directory, and «check off» (delete) each one as I went from the «list» (hash map or binary tree) in memory.

Except depending on the exact use case, maybe instead of deleting entries from a hash map or tree, I would keep track of a «do I have this file?» boolean for each entry, and figure out a data structure that would make it O(1) to ask «do I have every file?». Maybe a binary tree but the struct for each non-leaf node also has a boolean that is a logical-and of the booleans of its leaf nodes. That scales well — after setting a boolean in a leaf node, you just walk up the tree and set each node’s «have this?» boolean with the && of its child node’s boolean (and you don’t need to recurse down those other child nodes, since if you’re doing this process consistently every time you go to set one of the leaves to true, they will be set to true if and only if all of their children are.)

Sadly, there is no standard way to do it until C++17.

Of course there is a corresponding boost::filesystem::directory_iterator which I presume will work in older versions of C++.

The closest thing to a standard C way is opendir and readdir from dirent.h . That is a standard C interface, it’s just standardized in POSIX and not in the C standard itself. It comes is available out-of-the-box on Mac OS, Linux, all the BSDs, other UNIX/UNIX-like systems, and any other POSIX/SUS system. For Windows, there is a dirent.h implementation that you just have to download and drop into your include path.

However, since you’re looking for the fastest way, you might want to look beyond the portable/standard stuff.

On Linux, you might be able to optimize your performance by manually specifying the buffer size with the raw system call getdents64 .

On Windows, after a bit of digging, it looks like for maximum performance you want to use FindFirstFileEx with FindExInfoBasic and FIND_FIRST_EX_LARGE_FETCH when you can, which a lot of the open source libraries like the above dirent.h for Windows don’t seem to do. But for code that needs to work with stuff older than the last couple Windows versions, you might as well just use the straightforward FindFirstFile without the extra flags.

Plan 9 won’t be covered by any of the above, and there you’ll want dirread or dirreadall (the latter if you can safely assume you have enough memory for the entire directory contents). If you want more control over the buffer size for performance use plain read or read and decode the directory entry data — they’re in a documented machine-independent format and I think there’s helper functions provided.

I don’t know about any other operating systems.

I might edit this answer with some tests later. Others are welcome to edit in test results as well.

Читайте также:  Как установить windows офис с диска с
Оцените статью