Is file is readable windows

File_exists,is_writable ,is_readable — проверка файлов

При работе с файлами зачастую появляется необходимость проверки состояния самих файлов (проверить файл на существование, проверить можно ли производить запись, чтение и т.д.). И тут нам на помощь приходят функции -file_exists,is_writable ,is_readable.

Функция file_exists

Функция file_exists() позволяет определить существует ли требуемый файл. Имеет следующий синтаксис:

file_exists (имя файла или директории)

Функция file_exists() является логической функцией, то есть в случае обнаружения требуемого файла возвращает значение TRUE, в противном случае – FALSE.

Требуемый файл НЕ существует

В данном примере мы использовали функцию file_exists() для определения существования файла file1.txt . В программе мы используем оператор условия If и выводим сообщение о существовании файла, в зависимости, от результата, полученного if .

Функция is_writable

Использовав функцию is_writable() мы можем определить, можно ли производить запись в файл:

is_writable (имя файла )

Как и в случае с функцией file_exists() данная функция является логической и возвращает TRUE в случае, если запись в файл возможна и FALSE в обратном случае.

Функция is_readable

Функция is_readable() позволяет определить возможность чтения из файла:

is_readable (имя файла)

В случае возможности чтения из файла функция возвращает TRUE и FALSE – в обратном случае.

Исключительно
для моих подписчиков доступен мощный мини-курс по проектированию SEO текстов, которые сами выходят в ТОП!

Подписывайся на рассылку и получишь
это руководство полностью БЕСПЛАТНО

is_readable — Определяет существование файла и доступен ли он для чтения

(PHP 4, PHP 5, PHP 7)

is_readable — Определяет существование файла и доступен ли он для чтения

Описание

Возвращает TRUE , если файл существует и доступен для чтения.

Список параметров

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

Возвращает TRUE , если файл или директория, указанная в filename существует и доступна для чтения, иначе возвращает FALSE .

Примеры

Пример #1 is_readable() example

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Читайте также:  Crack для windows sp2

Примечания

Не забывайте, что PHP может обращаться к файлам от имени пользователя, от которого запущен веб-сервер (часто ‘nobody’). До версии PHP 5.1.5 ограничения безопасного режима не принимались во внимание.

Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обертками url. Список оберток, поддерживаемых семейством функций stat() , смотрите в Поддерживаемые протоколы и обработчики (wrappers).

Проверка производится с использованием реальных UID/GID вместо эффективных.

Эта функция может возвращать TRUE для директорий. Чтобы отличить файл от директории можно воспользоваться функцией is_dir() .

Смотрите также

  • is_writable() — Определяет, доступен ли файл для записи
  • file_exists() — Проверяет наличие указанного файла или каталога
  • fgets() — Читает строку из файла

is_readable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_readable — Определяет существование файла и доступен ли он для чтения

Описание

Возвращает true , если файл существует и доступен для чтения.

Список параметров

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

Возвращает true , если файл или директория, указанная в filename существует и доступна для чтения, иначе возвращает false .

Примеры

Пример #1 is_readable() example

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примечания

Не забывайте, что PHP может обращаться к файлам от имени пользователя, от которого запущен веб-сервер (часто ‘nobody’). До версии PHP 5.1.5 ограничения безопасного режима не принимались во внимание.

Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.

Проверка производится с использованием реальных UID/GID вместо эффективных.

Эта функция может возвращать true для директорий. Чтобы отличить файл от директории можно воспользоваться функцией is_dir() .

Смотрите также

  • is_writable() — Определяет, доступен ли файл для записи
  • file_exists() — Проверяет существование указанного файла или каталога
  • fgets() — Читает строку из файла

How to check if a file exists and is readable in C++?

I’ve got a fstream my_file(«test.txt»), but I don’t know if test.txt exists. In case it exists, I would like to know if I can read it, too. How to do that?

8 Answers 8

I would probably go with:

The good method checks if the stream is ready to be read from.

Читайте также:  Linux python mysql python

You might use Boost.Filesystem. It has a boost::filesystem::exist function.

I don’t know how about checking read access rights. You could look in Boost.Filesystem too. However likely there will be no other (portable) way than try to actually read the file.

What Operating System/platform?

On Linux/Unix/MacOSX, you can use fstat.

On Windows, you can use GetFileAttributes.

Usually, there is no portable way of doing this with standard C/C++ IO functions.

if you are on unix then access() can tell you if it’s readable. However if ACL’s are in use, then it gets more complicated, in this case it’s best to just open the file with ifstream and try read.. if you cannot read then the ACL may prohibit reading.

Since C++11 it’s possible to use implicit operator bool instead of good() :

Consider also checking for the file type.

I know the poster eventually said they were using Linux, but I’m kind of surprised that no one mentioned the PathFileExists() API call for Windows.

You will need to include the Shlwapi.lib library, and Shlwapi.h header file.

the function returns a BOOL value and can be called like so:

Concerning the use of fstat in windows, I am not sure if it is what you want. From Microsoft the file must be already open. Stat should work for you.

How to check if a file is readable?

I’m writing Java 6 application and I have to check if a file is readable. However, on Windows canRead() always returns true . So I see that probably, the only solution could be some native solution based on WINAPI and written in JNA/JNI.

But, there is another problem, because it’s difficult to find a simple function in WINAPI which would return information about access to a file. I found GetNamedSecurityInfo or GetSecurityInfo but I’m not an advanced WINAPI programmer and they are too complicated for me in connection with JNA/JNI. Any ideas how to deal with this problem?

5 Answers 5

Java 7 introduced the Files.isReadable static method, it accepts a file Path and returns true if file exists and is readable, otherwise false.

Tests whether a file is readable. This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for reading. Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.

Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

Читайте также:  Сборка windows extreme edition

Try to use the following code

You could use FilePermission and AccessController tougher in this way :

If a requested access is allowed, checkPermission returns quietly. If denied, an AccessControlException is thrown.

You only need to know if it’s readable if you are going to read it. So, just try to read it, when you need to, and deal with it if you can’t. The best way to test the availability of any resource is just to try to use it and deal with the exceptions or errors as they arise. Don’t try to predict the future.

It can be perfectly reasonable to check accessibility of a resource (readability of a file in this case) long before the actual usage of that resource.

Imagine a server application which will use a subcomponent which will read a particular file in some circumstances some time later. It can be useful to check the readability of the file at server startup and WARN if it’s not readable. Then somebody can fix the situation (make the file readable, anything) before the circumstances actually causes the subcomponent to try to read that file.

Of course, this upfront check is not a substitute for proper exception handling in the sub component (it’s very possible that the file is readable at start but became unreadable later).

So the question about pre-checking is perfectly valid I think.

As for the method of checking the resource, try to do something as similar as possible to actual usage. If later the file will be read, then try to read it!

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