我正在使用C,有时我必须处理类似的路径
有没有办法检查给定路径是目录还是给定路径是文件?
给定一个路径,比如/ home/shree/path/def,我想确定def是目录还是文件.有没有办法在C或C++代码中实现这一点?
这是我写的一个C程序,用于递归导航和输出目录和常规文件.它在我的Linux机器上编译并运行良好.但是在Solaris上,dit->d_type == 8检查和其他类似检查不起作用,因为没有d_type字段.我已经阅读过这个问题的答案是使用S_ISREG()和S_ISDIR()宏,但它们并不能完全按照我目前的代码中的方式工作.我注释掉了在我的Linux机器上运行的行.
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/ …Run Code Online (Sandbox Code Playgroud) 当我做:
FILE * fp = fopen("filename", "r");`
Run Code Online (Sandbox Code Playgroud)
我怎么知道文件指针fp指向文件或目录?因为我认为两种情况下fp都不会为空.我能做什么?
环境是UNIX.
我正在尝试使用 open() 在 c 中打开一个文件,并且我需要检查该文件是否是常规文件(它不能是目录或块文件)。每次我运行 open() 时,我返回的文件描述符都是 3 - 即使我没有输入有效的文件名!
这是我所拥有的
/*
* Checks to see if the given filename is
* a valid file
*/
int isValidFile(char *filename) {
// We assume argv[1] is a filename to open
int fd;
fd = open(filename,O_RDWR|O_CREAT,0644);
printf("fd = %d\n", fd);
/* fopen returns 0, the NULL pointer, on failure */
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何验证输入文件?谢谢!