如何在C中检查文件是否处于只读模式

How to check if a file is in read-only mode in C

如何在 C 中检查文件是否处于只读模式?我想检查是否可以在打开文件之前写入文件。

您可以使用 fstat() 函数。 详情参见man 2 fstat: http://linux.die.net/man/2/fstat

您可以使用 fopen,并检查 return 值。在这里查看:http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm

在这种情况下,尝试打开文件进行写入并在打开失败时做出适当反应 ('Easier to Ask for Forgiveness than for Permission') 比首先尝试确定它是否会失败 ('Look Before You Leap') — 参见 LBYL vs EAFP.

您可以使用 stat(), but it is modestly tricky to determine the permissions correctly. Also, there could be ACLs that mean you can access the file for writing even if the permissions reported by stat() indicate that you can't (or vice versa). You could use access(filename, W_OK),它通常会给您正确的答案 — 除非您的程序 运行 有效 UID 与实际 UID 不同。

但是,任何 LBYL 策略也会遇到 TOCTOU(检查时间、使用时间)问题。文件或指向它的目录之一的权限可能会在您检查文件权限的时间和您实际尝试打开文件的时间之间发生变化。权限可能显示 "it is OK" 但文件可能已被删除,或从那时起更改为只读。

虽然使用 fstat/stat 函数检索文件权限会给你很好的提示是通常的情况,但我建议不要过分相信它们,因为有角落的地方文件将是可写的,尽管被报告为只读,例如,如果您是 root,以及尽管被报告为可写,但您将无法写入文件的情况,例如,如果它位于只读文件系统上。

ACL 也可能通过颠倒 st_mode 报告的内容来发挥类似的混淆作用。