Nel*_*tin 3 c file system-calls
我正在尝试使用 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 */
}
谁能告诉我如何验证输入文件?谢谢!
尝试这个:
int file_isreg(const char *path) {
    struct stat st;
    if (stat(path, &st) < 0)
        return -1;
    return S_ISREG(st.st_mode);
}
1如果正常,此代码将返回,0如果不是,-1则出错(带errno设置)。
如果您想通过 返回的文件描述符检查文件open(2),请尝试:
int fd_isreg(int fd) {
    struct stat st;
    if (fstat(fd, &st) < 0)
        return -1;
    return S_ISREG(st.st_mode);
}
您可以在此处找到更多示例(特别是在path.c文件中)。
您还应该在代码中包含以下标头(如stat(2)手册页所述):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
为了供将来参考,以下是stat(2)有关可用于st_mode字段验证的 POSIX 宏的联机帮助页摘录:
S_ISREG(m)  is it a regular file?
S_ISDIR(m)  directory?
S_ISCHR(m)  character device?
S_ISBLK(m)  block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m)  symbolic link?  (Not in POSIX.1-1996.)
S_ISSOCK(m) socket?  (Not in POSIX.1-1996.)