有没有一种简单的方法来判断文件流是否打开了目录而不是文件?
我正在制作一个 HTTP 服务器,当我获得他们请求的文件的路径时,我使用以下命令打开它:
returned_file = fopen(path, "r");
即使路径是目录,这(与我的想法相反)也会成功。有没有一种简单的方法来检查 returned_file 流是否是目录而不是文件?
I'm making an HTTP server and when I get the path of the file they request I open it with the following:
returned_file = fopen(path, "r");
this (contrary to what I would think) succeeds even if the path is a directory. Is there an easy way to check if the returned_file stream is a directory instead of a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以对 fopen 返回的文件描述符使用 fstat。
编辑:
这是示例程序:
you can use fstat on the file descriptor returned by fopen.
Edit:
Here's and example program:
详细说明其他答案,您可以在返回的文件描述符上调用 fstat 并检查
st_mode
中的S_IFDIR
位。 S_ISDIR 辅助宏很有帮助:...
Elaborating on the other answers, you can call fstat on the returned file descriptor and check the
st_mode
for theS_IFDIR
bit. The S_ISDIR helper macro is helpful:...
您可以在调用 fopen 之前检查路径是否指向目录吗?
Can you check if the path points to a directory before you call fopen?
在打开文件名之前使用 stat(),或者使用 fstat() 文件描述符 fileno(returned_file)。
Use stat() on the file name before you open it, or fstat() the file descriptor fileno(returned_file).