繁体   English   中英

if(fp:= EOF) -> 警告:指针与 integer 之间的比较

[英]if(fp != EOF) -> Warning: Comparison between pointer and integer

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

int main()
{
    FILE *fp;

   char written[]= "This is not as easy as I thought it would be.";
    fp = fopen("Aufgabe 3.txt", "w");
    if(fp != EOF)
    {
        fprintf(fp, "%s", written);
        printf("Text was written!\n");
    }
    else
    {
        printf("File can not be found!");
    }
    fclose(fp);

    return 0;
}

嗨,我是编码新手,需要一点帮助。 :D

有谁知道如何摆脱警告,我只是想将一句话写成a.txt。

行警告:10 if(fp != EOF)

指针与integer比较

The fopen function returns a pointer to the newly opened file stream or, on error, a NULL pointer (which is not the same as the EOF integer constant). 改用这个:

    if(fp != NULL)
    {
        fprintf(fp, "%s", written);
        printf("Text was written!\n");
    }
    else
    {
        printf("File can not be found!");
    }

The variable fp is a pointer so you should compare it with NULL, not EOF which is an integer (see the reference documentation for fopen : https://pubs.opengroup.org/onlinepubs/9699919799/ ).

  1. 你应该在文件中写入一个换行符(为了它是一个文本文件)
  2. 错误应打印到标准错误 stream
  3. 打印打开文件失败的原因是个好主意
  4. 程序应在失败时退出并显示错误代码
  5. 仅当打开文件成功时才应调用fclose
  6. 由于写入的变量没有被修改,它可以变成一个指针常量。

这是一个更正的版本:

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

int main()
{
    const char *filename = "Aufgabe 3.txt";
    const char *written = "This is not as easy as I thought it would be.";
    FILE *fp;

    fp = fopen(filename, "w");
    if (fp != NULL) {
        fprintf(fp, "%s\n", written);
        printf("Text was written!\n");
        fclose(fp);
    } else {
        fprintf(stderr, "Opening file '%s' failed: %s:\n", filename, strerror(errno));
        exit(EXIT_FAILURE);
    }
    return 0;
}

EOF是负 integer 常数的宏。 fp是指向FILE的指针。

如果你使用

if (fp != EOF)

您将指针与非零值的 integer 进行比较,这是不允许的。

NULL替换EOF ,这是一个用指针检查错误的宏:

if (fp != NULL)

旁注:

  • 此外,您应该只在指向已成功打开的 stream 的指针上使用fclose() 如果fpNULL时使用flose(fp) ,则程序具有未定义的行为

  • 此外,使用if (fp != NULL)检查 stream 的打开是否没有错误,然后当 stream 成功打开文件时继续进入if s 正文。 else如果打开不成功你把go放到else体中。

    这段代码可以简化。

    只需检查是否发生了错误,如果是,则通过if正文中的错误例程。 如果不是,则控制流立即继续到if语句之后的main()中的代码。 不需要else

  • 您的错误例程应该在生产代码中得到增强。 仅仅打印出文件打开不成功是不够的。


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

int main (void)
{
    FILE *fp;

    char written[] = "This is not as easy as I thought it would be.";

    fp = fopen("Aufgabe 3.txt", "w");
    if (fp == NULL)
    {
        perror("fopen: ");
        exit(EXIT_FAILURE);
    }

    fprintf(fp, "%s", written);
    printf("Text was written!\n");

    fclose(fp);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM