检查在Windows / Linux中对文件的写入权限 [英] Check for writing permissions to file in Windows/Linux
问题描述
我想知道如何检查是否对文件夹具有写入权限。
I would like to know how to check if I have write permissions to a folder.
我正在写一个C ++项目,我应该打印一些数据到result.txt文件,但我需要知道是否有权限。
I'm writing a C++ project and I should print some data to a result.txt file, but I need to know if I have permissions or not.
Linux和Windows之间的检查是否不同?因为我的项目应该在Linux上运行,目前我在Visual Studio中工作。
Is the check different between Linux and Windows? Because my project should run on Linux and currently I'm working in Visual Studio.
推荐答案
尝试打开文件并检查是否成功。如果没有,并且 errno
(从标题 < cerrno>
设置为值 EACCES
[yes,with one S],那么您没有足够的权限。这应该同时适用于 Unix / Linux 和 Windows 。stdio的示例:
The portable way to check permissions is to try to open the file and check if that succeeded. If not, and errno
(from the header <cerrno>
is set to the value EACCES
[yes, with one S], then you did not have sufficient permissions. This should work on both Unix/Linux and Windows. Example for stdio:
FILE *fp = fopen("results.txt", "w");
if (fp == NULL) {
if (errno == EACCES)
cerr << "Permission denied" << endl;
else
cerr << "Something went wrong: " << strerror(errno) << endl;
}
Iostreams的工作方式略有不同,AFAIK,他们不保证设置
Iostreams will work a bit differently. AFAIK, they do not guarantee to set errno
on both platforms, or report more specific errors than just "failure".
正如Jerry Coffin写的那样,不要依赖这些错误在单独的访问测试功能,因为您的程序将容易出现竞争条件和安全漏洞。
As Jerry Coffin wrote, don't rely on separate access test functions since your program will be prone to race conditions and security holes.
这篇关于检查在Windows / Linux中对文件的写入权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!