Как проверить наличие файла c
Checking the presence of a directory or a file is one of the most common operations performed by a file system in an Operating System. Most programming languages offer some level of file system accessibility in form of library functions. In this article, you will learn how to test a file or directory that exists in C++.
Note: stat function present in the sys/stat.h header file would be used in the program. The function is not a part of the C++ standard library.
Checking/Testing the presence of a directory
stat is a pre-defined function present in the sys/stat.h header file. The function takes a path and a structure as arguments in which the metadata associated with the file/directory if present would be stored. The function returns the value of 0 if the path is a valid one. For demonstration we would be testing the presence of the following directory:
Example:
Output:
Explanation: Firstly, the path to the directory is stored in the dir pointer variable. Then the empty structure is initialized with the format that is present in the stat header file. This would store the metadata. Then, inside the if condition where a call to the stat function is made. If the path is valid i.e. the file/directory exists, then the output would be 0, otherwise, it would be non-zero. Hence if the condition would be true if the path is valid, otherwise the else block would be executed, displaying The Path is invalid! message.
Checking/Testing the presence of a file
The aforementioned process could be used to identify the presence of a file inside a directory as well. With some minor changes to the prior code, the presence of files could also be tested. Therefore, in this example, the attempt to detect the following file would be made
Как проверить наличие файла c
Подобно паре Directory/DirectoryInfo для работы с файлами предназначена пара классов File и FileInfo . С их помощью мы можем создавать, удалять, перемещать файлы, получать их свойства и многое другое.
FileInfo
Некоторые полезные методы и свойства класса FileInfo :
CopyTo(path) : копирует файл в новое место по указанному пути path
Create() : создает файл
Delete() : удаляет файл
MoveTo(destFileName) : перемещает файл в новое место
Свойство Directory : получает родительский каталог в виде объекта DirectoryInfo
Свойство DirectoryName : получает полный путь к родительскому каталогу
Свойство Exists : указывает, существует ли файл
Свойство Length : получает размер файла
Свойство Extension : получает расширение файла
Свойство Name : получает имя файла
Свойство FullName : получает полное имя файла
Для создания объекта FileInfo применяется конструктор, который получает в качестве параметра путь к файлу:
Класс File реализует похожую функциональность с помощью статических методов:
Copy() : копирует файл в новое место
Create() : создает файл
Delete() : удаляет файл
Move : перемещает файл в новое место
Exists(file) : определяет, существует ли файл
Пути к файлам
Для работы с файлами можно применять как абсолютные, так и относительные пути:
Получение информации о файле
Удаление файла
Перемещение файла
Если файл по новому пути уже существует, то с помощью дополнительного параметра можно указать, надо ли перезаписать файл (при значении true файл перезаписывается)
Копирование файла
Метод CopyTo класса FileInfo принимает два параметра: путь, по которому файл будет копироваться, и булевое значение, которое указывает, надо ли при копировании перезаписывать файл (если true , как в случае выше, файл при копировании перезаписывается). Если же в качестве последнего параметра передать значение false , то если такой файл уже существует, приложение выдаст ошибку.
Метод Copy класса File принимает три параметра: путь к исходному файлу, путь, по которому файл будет копироваться, и булевое значение, указывающее, будет ли файл перезаписываться.
Чтение и запись файлов
В дополнение к вышерассмотренным методам класс File также предоставляет ряд методов для чтения-записи текстовых и бинарных файлов:
AppendAllLines(String, IEnumerable<String>) / AppendAllLinesAsync(String, IEnumerable<String>, CancellationToken)
добавляют в файл набор строк. Если файл не существует, то он создается
AppendAllText(String, String) / AppendAllTextAsync(String, String, CancellationToken)
добавляют в файл строку. Если файл не существует, то он создается
byte[] ReadAllBytes (string path) / Task<byte[]> ReadAllBytesAsync (string path, CancellationToken cancellationToken)
считывают содержимое бинарного файла в массив байтов
string[] ReadAllLines (string path) / Task<string[]> ReadAllLinesAsync (string path, CancellationToken cancellationToken)
считывают содержимое текстового файла в массив строк
string ReadAllText (string path) / Task<string> ReadAllTextAsync (string path, CancellationToken cancellationToken)
считывают содержимое текстового файла в строку
IEnumerable<string> ReadLines (string path)
считывают содержимое текстового файла в коллекцию строк
void WriteAllBytes (string path, byte[] bytes) / Task WriteAllBytesAsync (string path, byte[] bytes, CancellationToken cancellationToken)
записывают массив байт в бинарный файл. Если файл не существует, он создается. Если существует, то перезаписывается
void WriteAllLines (string path, string[] contents) / Task WriteAllLinesAsync (string path, IEnumerable<string> contents, CancellationToken cancellationToken)
записывают массив строк в текстовый файл. Если файл не существует, он создается. Если существует, то перезаписывается
WriteAllText (string path, string? contents) / Task WriteAllTextAsync (string path, string? contents, CancellationToken cancellationToken)
записывают строку в текстовый файл. Если файл не существует, он создается. Если существует, то перезаписывается
Как видно, эти методы покрывают практически все основные сценарии — чтение и запись текстовых и бинарных файлов. Причем в зависимости от задачи можно применять как синхронные методы, так и их асинхронные аналоги.
Например, запишем и считаем обратно в строку текстовый файл:
Стоит отметить, что при добавлении текста я добавил в строку последовательность «\n», которая выполняет перевод на следующую строку. Благодаря этому добавляемый текст располагается в файле на новой строке.
Если мы хотим, что в файле изначально шло добавление на новую строку, то для записи стоит использовать метод WriteAllLines/ WriteAllLinesAsync , а для добавления — AppendAllLines / AppendAllLinesAsync
Аналогично при чтении файла если мы хотим каждую строку файла считать отдельно, то вместо ReadAllText / ReadAllTextAsync применяется ReadAllLines / ReadAllLinesAsync .
What's the best way to check if a file exists in C?
Is there a better way than simply trying to open the file?
8 Answers 8
Look up the access() function, found in unistd.h . You can replace your function with
Under Windows (VC) unistd.h does not exist. To make it work it is necessary to define:
You can also use R_OK , W_OK , and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK )
Update: Note that on Windows, you can’t use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
std::filesystem:: exists
Checks if the given file status or path corresponds to an existing file or directory.
Contents
[edit] Parameters
s | — | file status to check |
p | — | path to examine |
ec | — | out-parameter for error reporting in the non-throwing overload |
[edit] Return value
true if the given path or file status corresponds to an existing file or directory, false otherwise.
[edit] Exceptions
No filesystem exception is thrown if object does not exist (use return value).
[edit] Notes
The information provided by this function is usually also provided as a byproduct of directory iteration. During directory iteration, calling exists ( * iterator ) is less efficient than exists ( iterator — > status ( ) ) .