tabs_over_spaces
tabs_over_spaces

Reputation: 362

reassign a file pointer in loop

I need to reassign a single file pointer to multiple files sequentially.

I have the file paths correctly in a string path.

when i pass the path and the file pointer to a function to reassign, I get "Aborted (core dumped)"..

FILE * fptr;        //Global file pointer
FILE * getfptrr(char * path)
{

    fclose(fptr);
    fptr = fopen(path, "r");

    if(fptr!=NULL)
        return fptr;
    else 
    {
        printf("\n Something's Wrong!!! \n");
        exit(1);
    }
}

Should I use frepoen?? and how...

Or any other options??

Upvotes: 2

Views: 616

Answers (2)

babalu
babalu

Reputation: 622

Are you calling the close() function:

[1] As a way to initialize the file pointer?

[2] Or are you trying to close a previously opened file?

If so:

[1] You can initialize the pointer with the following:

    fptr = NULL;
    fptr = fopen(path, "r");

[2] I would suggest to call close() in the same function where fopen() is used

I recommend you use an error return code instead of exit() as it's a more graceful way to terminate your program. Error codes make it easier to debug and follow program logic than having exit() functions throughout your code.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409442

You do not check that the fptr is not NULL before you call fclose.

Initialize fptr to NULL in the definition, and then check that it's not NULL before calling fclose (or freopen which is actually what you're doing here).

Upvotes: 4

Related Questions