c - 如何测试 FILE*(指向结构的指针)(如果 == NULL)?

标签 c pointers struct

我一直在玩 C,不管怎样,我在想文件指针(指向结构类型)如何立即测试是否为 NULL:

FILE *cfPtr;
if ( ( cfPtr = fopen( "file.dat", "w" ) ) == NULL )

我自己尝试这样做,但出现错误。

struct foo{
    int x;
};

struct foo bar = {0};

if (bar == NULL)
    puts("Yay\n");
else
    puts("Nay");

error C2088: '==' : illegal for struct

这是 stdio.h 文件中的 FILE 减速:

struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
        };
typedef struct _iobuf FILE;

最佳答案

它应该是一个指向结构的指针:

struct foo* bar = ...

if (bar == NULL)
    puts("Yay\n");
else
    puts("Nay");

确实可以测试指向结构的指针是否为空,就像指向原始类型的指针一样。

关于c - 如何测试 FILE*(指向结构的指针)(如果 == NULL)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2957549/

相关文章:

c - 使用结构时出错,C

c++ - #define 中的## 是什么意思?

c++ - read() 缓冲区有无效数据(指针问题?)

c - 在 C 中,将结构作为参数传递给 printf 的预期行为是什么?

c++ - C++将结构传递给函数以访问嵌套结构

ios - Swift 结构在自定义框架中不可见

c++ - 列出目标文件中 undefined reference

C++ 创建原子函数

c++ - 智能指针模板和自动删除指针

括号内的 C++ 指针