我正在尝试制作一个处理文件和目录的简单程序,但我有两个主要问题:
- 如何检查文件或目录是否存在,以及
- 我怎么知道它是文件、目录、符号链接(symbolic link)、设备、命名管道等?目前主要是文件和目录很重要,但我也想知道其他的。
编辑: 所有那些建议使用 stat()
或类似函数的人,我已经研究过了,虽然它可能会回答我的第一个问题问题,我不知道它会如何回答第二个问题...
最佳答案
既然你在询问命名管道/符号链接(symbolic link)等,你可能在 *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(....) {
}
SE 文档 here对于您可以使用的 S_ISXXX 宏。
关于c - 如何判断一个文件或目录是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3543231/