简体   繁体   中英

Return pointer from function C

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 doing 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* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM