如何找出文件是否存在? [英] how to find out if a file exists?

查看:62
本文介绍了如何找出文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种可移植的方法来查找文件是否存在?

Is there a portable way of finding out if a file exists?

推荐答案

Good Old fopen()可以解决问题

Good Old fopen() does the trick

FILE *fp;
if ((fp = fopen((LPCTSTR)fName, "r")) == NULL)
{
  // file doesn't exist
}
else
{
  fclose(fp);
  // file does exist
}



(已更新)

如果您要拒绝答案,至少要有礼貌地说明原因. "fopen()"不起作用吗?当然,在所有平台上,它都是C和C ++.另一个解决方案指向一个链接,该链接概述了几种方法,但需要第三方(增强)或使用在Windows和Linux中具有不同名称的函数(_access(),access()),而这些函数并非代码透明"的,这意味着您必须对平台的代码进行条件化.如果要执行此操作,则最好使用特定于平台的调用,并放弃与平台无关的调用的想法.

我并不是说这是理想"或唯一"的答案,我是说它回答了OP提出的问题,而不是不好的答案",也许只是您不愿回答的一个问题"就像,但没有错.



(Updated)

If you''re going to downvote the answer, at least have the courtesy to say why. Does "fopen()" not work? Of course it does, on all platforms, C and C++. The other solution points to a link that outlines several ways but require 3rd party (boost) or use functions that have different names for Windows and Linux (_access(), access()) which isn''t "code transparent", meaning that you have to conditionalize the code for platform. If you''re going to do that, you might as well use the platform specific calls and give up the idea of platform agnostic calls.

I''m not saying this is the "ideal" or "only" answer, I''m saying it answered the OPs question as posed and is not a "bad answer", maybe it''s just one you don''t like, but not wrong.



这篇关于如何找出文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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