Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查输入文件是否是C中的有效文件_C_File_System Calls - Fatal编程技术网

检查输入文件是否是C中的有效文件

检查输入文件是否是C中的有效文件,c,file,system-calls,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;

我正在尝试使用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);
}
您可以找到更多示例(特别是在
path.c
文件中)

您还应该在代码中包含以下标题(如
stat(2)
manual页所述):


错误:检查文件是否正常,如果正常,打开并使用它

右:打开它。如果你做不到,就报告问题并摆脱困境。否则,请使用它(在每次操作后检查并报告错误

原因:您刚刚检查了一个文件是否正常。这很好,但您不能假设从现在起0.000000017秒内一切正常。也许磁盘会过热并损坏。也许其他进程会批量删除整个文件集合。也许你的猫会被网线绊倒。让我们再检查一下它是否正常,然后打开它。哇,好主意!不,等等

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 */

}

您正在使用0_CREAT,如果文件不存在,它会提示函数创建。在表中,它的编号是3(0,1,2是std输入std输出和std错误)

我认为查看fd不会解决问题,它只是RAM中存储文件的点。。。如果不为空,则表示可以打开该文件。可能重复的文件如何检查该文件是否为常规文件?如果文件不存在,你会告诉它创建文件(
O_create
)。好消息是stat也可以在windows上工作,尽管不是每个S_*宏都可用。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
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.)
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 */

}