Take the 2-minute tour ×

I can't open a file in C, even though the file exists and isn't used by any application. Can someone tell me what is causing this problem?

int main()
    FILE* oud;
    unsigned size;
    unsigned* bytes;
    char path[] = "C:\\Users\\Ruben\\Documents\\test.txt";
    errno_t error;

    if ((error  = fopen_s(&oud, path, "rb" )) == NULL)
        return -1;

    return 0;

The output is: "No error".

share|improve this question
I don't know what the error could be, but the reason why you don't get a useful error message is likely because you call perror(NULL); instead of checking the error code returned by fopen_s. –  Philipp Oct 15 '12 at 14:12
add comment

2 Answers

up vote 7 down vote accepted

fopen_s() returns 0 on success, not NULL on failure:

Zero if successful; an error code on failure. See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes.

The NULL macro is #defined to 0 (probably) which means if the file is opened the if() in the posted code is:

if (0 == 0)

which is obviously true. Change to:

if ((error = fopen_s(&oud, path, "rb" )) != 0)
share|improve this answer
add comment

...and you receive the file pointer in the oud variable, since it's passed as a reference. So after calling fopen_s, which on success returns 0, you then normally use oud for further operations.

share|improve this answer
add comment

Your Answer


