错误:控制可能达到非无效函数 - cat 函数的末尾


char *wcat(char *str, size_t n, FILE *fp){
if (fp == NULL) {
printf("wcat cannot open filen");
fclose(fp);
perror("File cannot be opened");
return NULL;
exit(1); 
}else{
if ((str = fgets(str,n,fp)) != NULL){
printf("%s",str);
return str;
exit(0);
}
}
}

终端:

gcc -o wcat wcat.c
Error: wcat.c:36:1: warning: control may reach end of non-void function [-Wreturn-type]

fp 已经等于 fopen(...(。

我不确定为什么会发生这种情况。我想创建这个 wcat 文件来工作,如下所示:

./wcat file1.c file2.c 

你的 else 子句也需要一个else,或者至少需要一个默认返回。您的if并不能涵盖所有可能的情况。警告准确地说明了问题所在。

char *wcat(char *str, size_t n, FILE *fp){
if (fp == NULL) {
printf("wcat cannot open filen");
fclose(fp);
perror("File cannot be opened");
return NULL;
//exit(1); 
}
else if (fgets(str,n,fp))
{
printf("%s",str);      
return str;
// exit(0);
}
return NULL; /// or whatever it is that you expect to happen here.
}

exit的呼吁都没有意义。他们永远不会被处决。看起来您正在尝试使用这些来返回某种成功/失败标志,但是:

  1. 他们从不执行,因为他们遵循return
  2. exit终止程序。

参数将传递回调用进程。根据我的经验,除非您正在编写控制台实用程序,否则基本上永远不会使用它。

你真的了解exit是做什么的吗?return呢?

这个有很多问题。我建议在调试器中单步执行。

以下带有注释的更改是处理此函数的正确方法:

char *wcat(char *str, size_t n, FILE *fp){
// note: this check should have been handled 
// where/when 'fopen()' was called
if (fp == NULL) {
// this changes the value in 'errno' 
// so 'perror() will not display the right message
//printf("wcat cannot open filen"); 
//fclose(fp);         // <-- never open'd so cannot close
perror("File cannot be opened");
return NULL;
//exit(1);            // <-- will never be executed
}else{
if (fgets(str,n,fp)){
printf("%s",str);
return str;
//exit(0);        // <-- will never be executed
}
return NULL;         // <-- need to handle when 'fgets()' fails
}
}

应用更正并移动检查"fopen(("失败后,代码将如下所示:

char *wcat(char *str, size_t n, FILE *fp)
{
if ( fgets( str, n, fp ) )
{
printf("%s",str);
return str;
}
return NULL; 
}

最新更新