在Unix中区分管道和文件

时间:2009-05-22 20:12:12

标签: c unix file pipe manpage

给定FILE *,是否可以确定基础类型?也就是说,是否有一个函数可以告诉我FILE *是管道还是套接字还是常规的磁盘文件?

2 个答案:

答案 0 :(得分:8)

有一个fstat(2)功能。

NAME        stat,fstat,lstat - 获取文件状态

概要

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

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

您可以致电fileno(3)来获取fd。

然后你可以致电S_ISFIFO(buf)来解决问题。

答案 1 :(得分:3)

使用fstat()函数。但是,您需要使用fileno()宏从文件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);