[英]Error: Control may reach end of non-void function - cat function
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
的調用都沒有意義。 他們永遠不會被處決。 看起來您正在嘗試使用它們來返回某種成功/失敗標志,但是:
return
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 file\n");
//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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.