KJ0090
KJ0090

Reputation: 63

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);
    }
}

Upvotes: 6

Views: 4028

Answers (3)

anon
anon

Reputation:

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
}

Upvotes: 6

Paul Nathan
Paul Nathan

Reputation: 40309

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

An int is not a FILE*.

Upvotes: 0

McPherrinM
McPherrinM

Reputation: 4594

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.

Upvotes: 11

Related Questions