fopen() in C will not create file

Discussion in 'Mac Programming' started by tnsmart, Nov 3, 2015.

  1. tnsmart macrumors 6502

    Aug 23, 2008
    I am trying to use fopen() in my C program to create and then open a file on my Mac, but it will not create the file. I've tried using both absolute and relative paths and different mode arguments for fopen() (r/w/a/r+/w+/a+), but nothing will work. Calling perror() or strerror() just gives me "No such file or directory.", which I know. Code that I know works fine on Linux results in the same problem on OS X. I think it must be a permissions issue, but I'm not sure how to fix it.

    Any help is appreciated.
  2. Sciuriware macrumors regular


    Jan 4, 2014
    FILE* fp = fopen("data.dat","ab+");

  3. cqexbesd macrumors regular

    Jun 4, 2009
    "No such file or directory" suggests you are trying to create the file in a location that doesn't exist. Maybe post a small piece of code that illustrates the problem. You will also need to say which user you are running as and the permissions on the the directory you are trying to create the file in (e.g. if the path you pass to fopen is /path/to/directory/file then post the output of ls -ld /path/to/directory).
  4. Senor Cuete, Nov 9, 2015
    Last edited: Nov 9, 2015

    Senor Cuete macrumors regular

    Nov 9, 2011
    #include <errno.h>
    FILE *file;
    char errorString[512];
    errno = 0;
    if((file = fopen(pathFileName, “whatever”)) == NULL)
       printf("Failed to open file. error %d\n, errno);
       printf(“%s\n”, errorString);
    If it fails to open/create a file the file pointer will be NULL. errno will contain an error code. perror will give you an error message.[/CODE]

    C gives you the ability to test for errors and diagnose them. Most software is written like this. Not doSomething(), but if doSomething() fails, report error and take some action like exit(0).

Share This Page