开发者

fputs crashing in C on Mac with Xcode

开发者 https://www.devze.com 2022-12-25 06:45 出处:网络
I have a command line app and have the code chdir(\"/var\"); FILE *scriptFile = fopen(\"wiki.txt\", \"w\");

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 g开发者_如何学JAVAets to the first fputs(); call


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消