tags:

views:

94

answers:

3

Hi, I have a command line app and have the 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 an EXC_BAD_ACCESS when it gets to the first fputs(); call

+2  A: 

Probably the call to fopen() failed because you don't have write permissions in /var. In this case fopen() returns NULL and passing NULL to fputs() will cause an access violation.

sth
+1 check for error returns!
Stephen Canon
+2  A: 

Are you checking to make sure the file is properly being opened?

Normally you will need superuser privileges to write into /var, so this is likely your problem.

WhirlWind
+1  A: 

I already answered this in the comment and a couple people have told you what you've done wrong as answers but I decided to add a little sample code 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 if your file is not opened and it will describe why (in your case, access denied). You can make this work for testing by either 1) replacing your filename with something world writeable, like "/tmp/wiki.txt"; or 2) running your utility with privileges sudo ./your_command_name.

Jason Coco