0

I need to check if a file is writable, to display a warning message when users try to open a file that is not writable.

I found on the QT forums the following examples to check if a file is writable:

const QFileInfo info(fileName);
if (info.permission(QFile::WriteOwner | QFile::WriteGroup | QFile::WriteUser)) {
  qDebug() << "File is writable";
} else {
 qDebug() << "Read Only file";
}

// Or even simpler:
if (info.isWritable()) {
  qDebug() << "File is writable";
} else {
 qDebug() << "Read Only file";
}

But unfortunately the above examples only works if a file has a read-only attribute, like this (this file is simple txt and I marked it as read-only):

enter image description here

I found in QT forums that I should look at the file permissions first. So, as you can see my file is not a read-only file (this is the permission of the real file I'm working).

enter image description here

If I go to the security section of the file's properties, I realize that the file only has permissions to read and execute, and of course not to write.

enter image description here

I tried to get the file permissions with the following code, but it doesn't seem to work.

QFileDevice::Permissions p = QFile(fileName).permissions();

if (p & QFileDevice::ReadOwner)
{
    qDebug() << "Read file";
}
if (p & QFileDevice::WriteOwner)
{
    qDebug() << "Write file";
}
if (p & QFileDevice::ExeOwner)
{
    qDebug() << "Exec file";
}

output:

Read file
Write file

I tried with another variants like writeUser, but I get the same result.

Any idea or suggestion.

I'm using Windows 10.

Sorry, I can't share the file for testing.

BadRobot
  • 265
  • 1
  • 9

1 Answers1

0

I am not familiar with Qt, but this can be done with std::filesystem:

auto p = std::filesystem::status(file_name).permission();

if(p & std::filesystem::perms::owner_read) { ... }
if(p & std::filesystem::perms::owner_write) { ... }
if(p & std::filesystem::perms::owner_exec) { ... }

You can also create a filesystem::perms with the octal value:

if(p & std::filesystem::perms{0400}) { ... }

For more about different perms available values: https://en.cppreference.com/w/cpp/filesystem/perms

Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39
  • Hi, thanks for your answer. I really appreciate it. Do you know if there is a way to implement your suggestion in c++ 14?. It seems this is supported in c++ 17 – BadRobot Nov 22 '22 at 19:24
  • @BadRobot There is this [link about using the header ](https://stackoverflow.com/questions/10323060/printing-file-permissions-like-ls-l-using-stat2-in-c), but I don't know if it is available in Windows. – Ranoiaetep Nov 22 '22 at 21:25
  • @BadRobot You can also check out [Boost.Filesystem](https://www.boost.org/doc/libs/master/libs/filesystem/doc/index.htm), `std::filesystem` was implemented based on an older version of `Boost.Filesystem` – Ranoiaetep Nov 22 '22 at 21:26