Search code examples
cxcodemacosfopen

fopen() with full file path not creating file and no errors when checked in C using Xcode macOS


I am new to C and just started learning how to create and write files in Xcode. I know some Python and bash and have been able to read, write, append, create, delete, move text files but this issue has me a bit stumped.

Basically, I am trying to use fopen() to create and open a new .txt file in write mode. I tried just using the "filename.txt" method assuming the file created would be in the same folder as the project I currently have open. The build succeeded, but no new file was created in that folder. I tried looking for it in the cwd, but it wasn't there either. Next, I tried the full file path method to try and put it on my desktop, then tried the path to the project folder, then a simpler direct path to a new folder in my users/user/ folder. Every time the build succeeds but then no file can be found anywhere.

My first attempts to check for errors were using something like "if( perror() ) else {printf("Nothing wrong"}" which worked and returned "Nothing Wrong!"

Other people have had similar questions but it seems like they all got errors returned, I don't know how to troubleshoot it because there don't seem to be any errors other than that the file is not being created at the specified location.

Other notes that may be useful to know: I have a desktop on iCloud Drive, most files on my computer are stored at an iCloud/... location if you check "Get info."

int main() {

FILE * fpointer = fopen("C:/Users/(name)/Documents/c_projects/Giraffe/Giraffe/employees.txt", "w");


fclose(fpointer);

return 0;
}

Solution

  • There are two problems:

    1. "C:/Users/(name)/Documents/c_projects/Giraffe/Giraffe/employees.txt" is definitely not a Mac OS path, it looks rather like a Windows path. Probably you should use "/Users/(name)/Documents/c_projects/..."

    2. You don't check for errors. fopen returns NULL if it was not successful, but you ignore this and you call fclose with a NULL file pointer which is undefined behaviour.

    You want something like this:

    int main() {
      FILE * fpointer = fopen("some path", "w");
      if (fpointer != NULL)
      {
        do something with fpointer 
        ...
        fclose(fpointer)
      }
      else
      {
        // display error message and/or take appropriate action
      }
     
      return 0;
    }