简体   繁体   中英

Distinguishing a pipe from a file in Unix

Given a FILE*, is it possible to determine the underlying type? That is, is there a function that will tell me if the FILE* is a pipe or a socket or a regular on-disk file?

There's a fstat(2) function.

NAME stat, fstat, lstat - get file status

SYNOPSIS

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <unistd.h>

   int fstat(int fd, struct stat *buf);

You can get the fd by calling fileno(3) .

Then you can call S_ISFIFO(buf) to figure it out.

Use the fstat() function. However, you'll need to use the fileno() macro to get the file descriptor from file FILE struct.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

FILE *fp = fopen(path, "r");
int fd = fileno(fp);
struct stat statbuf;

fstat(fd, &statbuf);

/* a decoding case statement would be good here */
printf("%s is file type %08o\n", path, (statbuf.st_mode & 0777000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM