c - 为什么在 fopen() 中使用无效模式时 gcc 不给出警告或错误?

标签 c gcc file-io compiler-errors compiler-warnings

我正在用 C 语言练习 FILE IO 中的一些练习题。下面是其中一个程序。

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

int main()
{
    char fname[]="poem.txt";
    FILE *fp;
    char ch;
    fp = fopen ( fname, "tr");
    if (fp == NULL)
    {
    printf("Unable to open file...\n");
    exit(1);
    }
    while((ch =fgetc(fp)) != EOF)
    {
            printf("%c",ch);
    }
    printf("\n");

    return 0;
}

正如你在声明中所见

  fp = fopen ( fname, "tr");

模式“tr”不是有效模式(据我所知)。我期待 gcc 在编译上述程序时给出错误(或警告)。但是,gcc 在编译时不会给出任何错误(或警告)。

但是,正如预期的那样,当我运行程序时它退出打印“无法打开文件...”,这意味着 fopen() 返回 NULL ,因为打开文件时出错。

-bash-4.1$ ./a.out
Unable to open file...
-bash-4.1$

(文件 poem.txt 存在,所以这是因为给 fopen() 的模式无效。我通过将模式更改为“r”进行检查,它可以正常显示“poem.txt”的内容)

-bash-4.1$ ./a.out
THis is a poem.

-bash-4.1$

我原以为 gcc 会针对无效模式给出错误(或警告)消息。

为什么 gcc 对此不给出任何错误(或警告)?

最佳答案

编译器不检查你做了什么,它只检查语法。

但是,在运行时,如果代码是这样写的:

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

int main()
{
    char fname[]="poem.txt";
    FILE *fp;
    char ch;

    fp = fopen ( fname, "tr");
    if (fp == NULL)
    {
        perror( "fopen for poem.txt failed");
        exit( EXIT_FAILURE );
    }

    while((ch =fgetc(fp)) != EOF)
    {
            printf("%c",ch);
    }
    printf("\n");

    return 0;
}

然后输出正确的错误信息:

...$ ./无标题

打开 poem.txt 失败:参数无效

关于c - 为什么在 fopen() 中使用无效模式时 gcc 不给出警告或错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533024/

相关文章:

c - scanf 无法读取 C 中的字符串

c - 中断 for 循环内的 if 语句

c - gcc: fatal error : regex.h: 没有那个文件或目录

java - UNIX系统和Windows系统中读取.CSV文件的差异

c - 您在我提供的代码中选择一种代码而不是另一种代码的原因是什么?有什么建议可以改进它们吗?

c - 有没有办法在 Eclipse 中启用所有宏?

c - GCC 链接器 : move a symbol in a specified section

c++ - 尾随返回类型中 SFINAE 的 GCC 错误

c# - 检测打开文件上的文件删除

java - 读写文件 - Java 空空间