开发者

Return pointer from function C

开发者 https://www.devze.com 2022-12-14 00:18 出处:网络
In my C program this function is going to handle all the work of opening a specific file and then return the file pointer, so main or other functions can read the content by using fp, but so far i hav

In my C program this function is going to handle all the work of opening a specific file and then return the file pointer, so main or other functions can read the content by using fp, but so far i haven't been able to get this to work.

I'm just learning the language, so it is possible that i am doin开发者_Python百科g something very wrong.

int open_text_file(char text_file_name[])
{
    FILE *fp;

    if((fp = fopen(text_file_name, "r")) != 0)
    {
            return fp;
    }

    else
    {
            printf("Cannot open file \"%s\"\n", text_file_name);
    }
}


In the first line, you have

int open_text_file(char text_file_name[])

This declares the return type as an int What you should have is

FILE * open_text_file(char text_file_name[])

As well, in your "else" case, you should return something to indicate an error to the caller.

return NULL

is an appropriate choice. Make sure you check your return value when you call it, though.


The function is a bit pointless, as all it does is what fopen() does, plus the error message. This is not good design, as the error branch must also return a (presumably NULL) pointer, which then must be tested again in the calling code. Better would be simply to say:

FILE * fp = fopen( somefile, "r" );
if ( fp == NULL ) {
   fprintf( stderr, "Cannot open %s\n", somefile );
   exit(1);   // or whatever you need to do to handle the error
}


FILE* open_text_file(); needs to be the prototype.

An int is not a FILE*.

0

精彩评论

暂无评论...
验证码 换一张
取 消