在调试一些代码时,我得到了类似下面的内容:
#include<stdio.h>
int main()
{
FILE *fb = fopen("/home/jeegar/","r");
if(NULL == fb)
printf("it is null");
else
printf("working");
}
这里在fopen我提供了一个有点有效的路径名但不是文件名。不应该fopen返回NULL然后呢?但它不会返回null!
修改
如果我在fopen中提供path of valid directory
,则会打印working
:
如果我在fopen中提供path of invalid directory
,则会打印it is null
修改 规范说
Upon successful completion, fopen() shall return a pointer to the object
controlling the stream. Otherwise, a null pointer shall be returned.
所以这里是否设置了错误代码,它必须返回NULL
错误代码设置是对ISO C标准标准的扩展。
错误也未设置
#include<stdio.h>
#include <errno.h>
int main()
{
errno = 0;
FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)
printf("its null");
else
printf("working");
printf("Error %d \n", errno);
}
输出
workingError 0
答案 0 :(得分:3)
我认为在Unix中,所有内容(包括目录)都被认为是文件,所以fopen应该对它们起作用。
答案 1 :(得分:1)
posix手册页man 3p fopen
在错误部分中说:
如果出现以下情况,fopen()函数将失败:
[...]
EISDIR指定文件是一个目录,模式需要写入权限。
(强调我的)。由于您没有请求写入权限,并且您使用的路径可能是目录,因此该功能不会失败。
关于什么可以使用引用目录的FILE*
,我不知道。
答案 2 :(得分:1)
您可能非常清楚Linux系统上的所有内容都是一个文件,如果不是文件,那么它就是一个进程(更正和备注欢迎:))目录被视为列出其他文件的文件({ {3}});所以打开将目录作为文件读取是一个有效的操作,因此您不会收到任何错误。虽然不允许尝试写入它,但是如果你在写入或追加模式下打开目录,fopen操作将失败(这已经被很好地提及其他响应和fopen文档的链接)。大多数文件操作如read&amp;对此文件流的写入操作将失败,并显示错误,指出其是一个目录。只有使用可以找到的是使用fseek
到SEEK_END
&amp;找到文件的大小(本例中是目录)。 ftell
(最有可能得到4096的结果)
关于使用errno
获取有意义的消息,您可以使用位于stdio.h
和string.h
的{{3}}。传递将在错误消息之前添加的消息或errno
中的Reference from TLDP&amp;通过errno.h
中的{{1}}
希望这有帮助!
答案 3 :(得分:0)
如何检查错误?
您可以查看errno,例如:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
errno = 0;
fp = fopen("file.txt", "r");
if ( errno != 0 )
{
// Here you can check your error types:
perror("Error %d \n", errno);
exit(1);
}
}
您可以在http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html错误部分找到错误类型。