gpt4 book ai didi

c - 错误: Control may reach end of non-void function - cat function

转载 作者:行者123 更新时间:2023-11-30 18:33:03 25 4
gpt4 key购买 nike

char *wcat(char *str, size_t n, FILE *fp){

if (fp == NULL) {
printf("wcat cannot open file\n");
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 file\n");
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. 它们从不执行,因为它们遵循返回
  2. exit 终止程序。

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

你真的了解exit的作用吗?然后返回

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

关于c - 错误: Control may reach end of non-void function - cat function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com