检查文件是否可以用可移植的C打开 [英] Checking whether a file can be opened using portable C

查看:153
本文介绍了检查文件是否可以用可移植的C打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行快速检查的文件是否可以打开。它应该写在便携式C,或至少在Win32和POSIX系统的工作。的#ifdef是可接受的。

I'd like to perform a quick check whether or not a file can be opened. It should be written in portable C, or at least to work on Win32 and POSIX systems. #ifdefs are acceptable.

我试图避免这种情况:

int openable(const char*filename) {
    FILE *f = fopen(filename,"r");
    if (!f)
        return 0; /* openable */
    fclose(f);
    return 1; /* not openable */
}

这是我可以告诉STAT(),以最简单的形式,可以用来检查文件是否存在,但不检查它是否是真正打开。

From what I can tell stat(), in its simplest form, can be used to check if file exists, but not to check if it's actually openable.

推荐答案

POSIX标准的解决方案是访问(),这也是在Windows运行时为 _访问()

The POSIX standard solution is access(), which is also in the Windows runtime as _access().

我猜是性能稍微比 fopen()函数 + FCLOSE(),因为更好的:

I guess it is slighly better than fopen()+fclose() because:


  • 这是一个公知的,标准的解决方案,以测试一个文件的访问权限的问题

  • 这是非常可能更快,以较少的内存开销

当然,它只是作为易受比赛条件做这样的测试的任何其他方式。在某种程度上,要知道唯一安全的方法,如果一个文件是availble的阅读是打开它,并尝试读取,无需关闭它之间。即使这样,你仍然需要观察意外EOF,当然。 I / O是很难的。

Of course, it is just as susceptible to race conditions as any other way of doing such a test. In a way, the only safe way to know if a file is availble for reading is to open it and try to read, without closing it in between. Even then, you still need to watch for "unexpected" EOF, of course. I/O is hard.

这篇关于检查文件是否可以用可移植的C打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆