Why does fopen_s have the paramater FILE **_File rather then the FILE *_File that fopen has? And what is the difference between those two functions?

Edited 5 Years Ago by tomtetlaw: n/a

Why does fopen_s have the paramater FILE **_File rather then the FILE *_File that fopen has?

Standard fopen returns the FILE pointer, but fopen_s instead returns an error code. Thus, an output parameter in the form of a pointer to a pointer to FILE is used to "return" a handle to the opened file.

And what is the difference between those two functions?

My usual response to such a question is that fopen is standard and portable while fopen_s is not. Especially in the case of fopen_s, there's not much benefit because the only real change is fopen_s checks the file name and mode parameters for NULL. Personally, I'm not convinced that the "safe" library Microsoft is determined to bully us into (by way of deprecation warnings) is worth it.

Why does it need to have a FILE ** instead of a FILE *? It works the same way, you just have to put & infront of your FILE *, I don't understand. If I could see the source code of fopen_s it would be easier.

Why does it need to have a FILE ** instead of a FILE *?

fopen_s changes where the pointer points. Here's an example of what you think should work, but it doesn't because p is a copy of ptr and any changes to it will not be reflected by ptr:

#include <stdio.h>

static int a = 12345;
static int b = 54321;

void foo(int *p)
{
    p = &b;
}

int main(void)
{
    int *ptr = &a;

    printf("%d\n", *ptr);
    foo(ptr);
    printf("%d\n", *ptr);

    return 0;
}

This is the solution (note that it's identical to fopen_s' solution). An extra level of indirection means that *p is the same object as ptr, and any changes to one will be reflected in the other:

#include <stdio.h>

static int a = 12345;
static int b = 54321;

void foo(int **p)
{
    *p = &b;
}

int main(void)
{
    int *ptr = &a;

    printf("%d\n", *ptr);
    foo(&ptr);
    printf("%d\n", *ptr);

    return 0;
}

It's funny as I was coding something else I came across this same issue and solved it the same way, and then I thought "I should check that thread.." :)

Thanks for your answers.

This article has been dead for over six months. Start a new discussion instead.