【发布时间】:2023-06-28 15:41:01
【问题描述】:
当 path = "c:\" 时,以下代码不会写入文件 c:\err.txt,因为权限被拒绝。但它不会同时产生错误。相反,它输出“OK”。
如何检查权限是否允许写入?
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
bool writeLineToErr(string path, string err_line){
std::ofstream outfile(path+"err.txt", std::ios_base::app);
if(!outfile){
cout<<"Error 1 "+path+"err.txt"+" can't open file!";
return false;
}
if(outfile.fail()){
cout<<"Error 2 "+path+"err.txt"+" can't open file!";
return false;
}
outfile << err_line << endl;
cout<<"OK";
outfile.close();
return true;
}
int main(int argc, char** argv) {
writeLineToErr("c:\\","Some Line");
return 0;
}
【问题讨论】:
-
感谢您提出问题。请包含一个 main() 函数并提供一个Compilable, Minimal, Complete, and Verifiable Example。这有助于我们为您提供帮助。
-
@john-murray 可编译、最小、完整且可验证的示例 - 完成!
-
“我如何检查权限是否允许写入” -
stat()或access()有两种方法.. 但它仍然可能失败 (TOCTOU)。 -
@FrançoisAndrieux Per this
failbit如果无法打开文件,则设置。