Search code examples
cfopen

fopen in binary mode returns null to existing file


I have a binary file ('''simdisk.bin'''). I opened it in 'r' mode and i've no problems to read it. Now, i want to open it in binary mode (rb+) to write and read in binary, but i get a nill pointer.

I made a test.c file to try it with this main:

int main(int argc, char const *argv[])
{
 fp = fopen("simdisk.bin", "rb+");
 printf("Ptr: %p\n", fp);
 fclose(fp);
}

Solution

  • My guess is you don't have permission to write to the file, which is what you're requesting with the + modifier, and it has nothing to do with the binary thing (the b modifier).

    Try this, which will tell you the reason why it's unable to open the file - not found? no permission? etc.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <errno.h>
    
    int main(int argc, char *argv[])
    {
       FILE *fp = fopen("simdisk.bin", "rb+");
    
       if (fp == 0)
       {
           printf("Cannot open file: error=%s\n", strerror(errno));
           exit(EXIT_FAILURE);
       }
       printf("Ptr: %p\n", fp);
       fclose(fp);
    
       return EXIT_SUCCESS;
    }
    

    You can also test by changing the mode to "rb" - which wants read+binary but not update - and it's likely to work just fine because you're not asking to write to the file.