首页 > 解决方案 > C 中 if ....==NULL 的问题

问题描述

我有这个代码,注意它被缩短了。问题是如果文件存在,它仍然会覆盖它。自从我做任何编程以来已经 30 年了,所以请耐心等待。谢谢!

FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");  
            exit(0);
        }
    return pointer;
}

标签: cnullfopen

解决方案


如果您使用的是 C11 标准,则可以使用“x”参数来指定如果文件存在,则fopen()函数将失败。

供参考:http ://www.cplusplus.com/reference/cstdio/fopen/


推荐阅读