我正在用 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/