Reputation: 3
Why does this code produce the warning?
FILE* my_open_file(char* filename)
{
FILE* fp=fopen(filename,"r");
if(fp==NULL)
{
perror("Error opening file");
return -1;
}
return fp;
}
fp is already a pointer, and not integer as far as I can see.
Upvotes: 0
Views: 152
Reputation: 96121
As others have said, you want to return a pointer in any case, because your function is declared to return a FILE *
. So, you should return NULL
if fopen()
fails, and the return value of fopen()
if it doesn't.
But then, your function is (almost) equivalent to fopen()
! In other words, you can replace your function by:
FILE* my_open_file(char* filename)
{
FILE *fp = fopen(filename);
if (fp == NULL) {
fprintf(stderr, "Unable to open file %s", filename);
perror(NULL);
}
return fp;
}
fopen()
isn't guaranteed to set errno
, so I added a fprintf()
call with the filename in addition to the perror()
call. Also, it's a good idea to print the filename in your error messages about failing to open a file.
Upvotes: 1
Reputation: 8586
You're returning -1 on error, which then must be implicitly cast to a FILE*
Upvotes: 0
Reputation: 6030
I think that this warning point to return -1
Instead of it just use "return NULL"
Upvotes: 2
Reputation: 139441
The compiler doesn't like return -1
, which is of type int
—but my_open_file
is supposed to return pointer-to-FILE
.
Use return NULL;
to signal error.
Upvotes: 7