[英]Distinguishing a pipe from a file in Unix
Given a FILE*, is it possible to determine the underlying type? 给定FILE *,是否可以确定基础类型? 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? 也就是说,是否有一个函数可以告诉我FILE *是管道还是套接字还是普通的磁盘文件?
There's a fstat(2)
function. 有一个fstat(2)
函数。
NAME stat, fstat, lstat - get file status NAME stat,fstat,lstat - 获取文件状态
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)
. 您可以通过调用fileno(3)
来获取fd。
Then you can call S_ISFIFO(buf)
to figure it out. 然后你可以调用S_ISFIFO(buf)
来搞清楚。
Use the fstat() function. 使用fstat()函数。 However, you'll need to use the fileno() macro to get the file descriptor from file FILE struct. 但是,您需要使用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.