如何确定文件或目录是否存在?

Frx*_*rem 1 c directory file

我正在尝试创建一个处理文件和目录的简单程序,但我有两个主要问题:

  • 如何检查文件或目录是否存在,以及
  • 我怎么知道它是文件,目录,符号链接,设备,命名管道等?主要是文件和目录现在很重要,但我也想知道其他人.

编辑:太多所有建议使用stat()或类似功能的人,我已经研究过了,虽然它可能会回答我的第一个问题,但我无法弄清楚它将如何回答第二个问题......

nos*_*nos 6

既然你正在查询命名管道/符号链接等,你可能在*nix上,所以使用 lstat()函数

struct stat info;

if(lstat(name,&info) != 0) {
  if(errno == ENOENT) {
   //  doesn't exist
   } else if(errno == EACCES) {
    // we don't have permission to know if 
   //  the path/file exists.. impossible to tell
   } else {
      //general error handling
   }
  return;
}
//so, it exists.

if(S_ISDIR(info.st_mode)) {
  //it's a directory
} else if(S_ISFIFO(info.st_mode)) {
  //it's a named pipe 
} else if(....) {
}
Run Code Online (Sandbox Code Playgroud)

这里是您可以使用的S_ISXXX宏的文档.