Check if input file is a valid file in C -
i trying open file in c using open() , need check file regular file (it can't directory or block file). every time run open() returned file discriptor 3 - when don't come in valid filename!
here's have
/* * checks see if given filename * valid file */ int isvalidfile(char *filename) { // assume argv[1] filename open int fd; fd = open(filename,o_rdwr|o_creat,0644); printf("fd = %d\n", fd); /* fopen returns 0, null pointer, on failure */ }
can tell me how validate input files? thanks!
try this:
int file_isreg(const char *path) { struct stat st; if (stat(path, &st) < 0) homecoming -1; homecoming s_isreg(st.st_mode); }
this code homecoming 1
if regular, 0
if not, -1
on error (with errno
set).
if want check file via file descriptor returned open(2)
, try:
int fd_isreg(int fd) { struct stat st; if (fstat(fd, &st) < 0) homecoming -1; homecoming s_isreg(st.st_mode); }
you can find more examples here, (specifically in path.c
file).
you should include next headers in code (as stated on stat(2)
manual page):
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h>
for future reference, here excerpt of stat(2)
manpage regarding posix macros available st_mode
field validations:
s_isreg(m) 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.)
c file system-calls
No comments:
Post a Comment