views:

151

answers:

3

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);
    }
}
+10  A: 

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.

McPherrinM
Perfect, now i'm able to pass argv[1] to the function and print the content from main. As many of you say, i should compare fp to NULL, why that?
KJ0090
On some uncommon platforms, NULL may not be 0. This isn't true in C++ however, or most places in practice.
McPherrinM
A: 

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

An int is not a FILE*.

Paul Nathan
+6  A: 

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
}
anon
+1, This function is really pointless.
nthrgeek