Fputs crashing in C on Mac with Xcode

I have a command line application and have code

chdir("/var"); FILE *scriptFile = fopen("wiki.txt", "w"); fputs("tell application \"Firefox\"\n activate\n",scriptFile); fclose(scriptFile); 

and when I run it in Xcode, I get EXC_BAD_ACCESS when it gets to the first call to fputs();

+4
source share
3 answers

The fopen() call probably failed because you do not have write permissions to /var . In this case, fopen() returns NULL , and passing NULL to fputs() will result in an access violation.

+2
source

Are you checking if the file is open correctly?

Typically, you will need superuser privileges to write to / var, so this is probably your problem.

+2
source

I already answered this in a comment, and a couple of people told you that you did differently from the answers, but I decided to add a small code example with error checking:

 chdir("/var"); FILE *scriptFile = fopen("wiki.txt", "w"); if( !scriptFile ) { fprintf(stderr, "Error opening file: %s\n", strerror(errno)); exit(-1); } else { fputs("tell application \"Firefox\"\n activate\n",scriptFile); fclose(scriptFile); } 

Now you will see an error message if your file is not open, and it will describe why (in your case access is denied). You can do this work for testing: 1) replacing your file name with something worldwide, for example, "/tmp/wiki.txt" ; or 2) running your utility with sudo ./your_command_name privileges.

+2
source

Source: https://habr.com/ru/post/1305904/


All Articles