[LCP]How to tell if a file is open?

Roberto Diaz rdiazmartin at vivaldi.dhis.org
Sat Sep 1 02:22:18 UTC 2001


> I'm writing a routine that need to check if the stream it is writing to is open
> before it writes to it.  for example,
> before I try to write and error messge to stdout, I want to make sure it is
> still open.  How can I do this?  All the
> file status functions I've come across require an open file.
> (I remember reading how to somewhere but I can't remember where.)

What is very likely that you remember are this macros at fstat(2)

 S_ISLNK(m)  is it a symbolic link?

              S_ISREG(m)  regular file?

              S_ISDIR(m)  directory?

              S_ISCHR(m)  character device?

              S_ISBLK(m)  block device?

              S_ISFIFO(m) fifo?

              S_ISSOCK(m) socket?


But to make sure if a file descriptor is a real file descritor what you
could to do is to make some operation on it and check if errno is set to
EBADF, something like this can make the trick:

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

inline int
isfildes (int fd)
{
  if (fcntl (fd, F_GETFL) < 0 && errno == EBADF)
    return 0;
  return 1;
}


---
Roberto Diaz <rdiazmartin at vivaldi.dhis.org>
..For a Brave GNU World..    
                                        Concerto Grosso Op. 3/8 A minor
                        Antonio Vivaldi (so... do you need beautiful words?)
                                                                      -----




More information about the linuxCprogramming mailing list