[英]Distinguishing a pipe from a file in Unix
给定FILE *,是否可以确定基础类型? 也就是说,是否有一个函数可以告诉我FILE *是管道还是套接字还是普通的磁盘文件?
有一个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)
来搞清楚。
使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.