Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 我的指针没有返回NULL,但它所在的文件不存在_C_Pointers - Fatal编程技术网

C 我的指针没有返回NULL,但它所在的文件不存在

C 我的指针没有返回NULL,但它所在的文件不存在,c,pointers,C,Pointers,我正在尝试使用fopen写入文件,如果打开文件时出错或文件不存在,则会进行空检查。然而,尽管文件不存在,指针返回一个任意数字,而不是NULL。为什么会发生这种情况?我如何纠正它 我的代码如下: #include<stdio.h> #include<stdlib.h> int writenumstofile(int num1, int num2) { FILE* fp; if ((fp = fopen("outpiuteuo.txt", "w")) =

我正在尝试使用fopen写入文件,如果打开文件时出错或文件不存在,则会进行空检查。然而,尽管文件不存在,指针返回一个任意数字,而不是NULL。为什么会发生这种情况?我如何纠正它

我的代码如下:

#include<stdio.h>
#include<stdlib.h>

int writenumstofile(int num1, int num2) 
{
    FILE* fp;

    if ((fp = fopen("outpiuteuo.txt", "w")) == NULL) {
        return 7;
        exit(1);
    }
    fprintf(fp, "%d", num1);
    fprintf(fp, "%d", num2);
    return 0;
}
#包括
#包括
int writenumstofile(int num1,int num2)
{
文件*fp;
if((fp=fopen(“outpiuteuo.txt”,“w”))==NULL){
返回7;
出口(1);
}
fprintf(fp,“%d”,num1);
fprintf(fp,“%d”,num2);
返回0;
}

如果文件不存在,它将创建一个文件。如果您不想创建文件,请使用
r+/code>文件,或者只需先在
r
模式下打开文件,然后继续使用
w
模式。

“将文件截断为零长度或创建文本文件进行写入。流位于文件的开头。”@Stargateur,谢谢,如果文件不存在,我不需要写入文件,我只需要指针返回null,有没有办法?我相信“r+”可以,当你想使用函数时读取。谢谢,这解决了问题,如果你只是将其更改为null,那么你将丢失一个指针,因此,您以后将无法关闭该文件。是否有办法阻止它这样做,并将其标记为null?@user10486019更新了我的答案。