7

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

4

2 回答 2

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);

您可以通过调用获取 fd fileno(3)

然后你可以打电话S_ISFIFO(buf)来弄清楚。

于 2009-05-22T20:17:49.337 回答
3

使用 fstat() 函数。但是,您需要使用 fileno() 宏从文件 FILE 结构中获取文件描述符。

#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);
于 2009-05-22T20:29:21.310 回答