[英]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.