我有一個命令行應用程序,並讓代碼的fputs在Mac上使用C崩潰和Xcode
chdir("/var");
FILE *scriptFile = fopen("wiki.txt", "w");
fputs("tell application \"Firefox\"\n activate\n",scriptFile);
fclose(scriptFile);
,當我在Xcode中運行它,我得到一個EXC_BAD_ACCESS當它到達第一fputs();
呼叫
我有一個命令行應用程序,並讓代碼的fputs在Mac上使用C崩潰和Xcode
chdir("/var");
FILE *scriptFile = fopen("wiki.txt", "w");
fputs("tell application \"Firefox\"\n activate\n",scriptFile);
fclose(scriptFile);
,當我在Xcode中運行它,我得到一個EXC_BAD_ACCESS當它到達第一fputs();
呼叫
由於您在/var
中沒有寫入權限,可能致電fopen()
失敗。在這種情況下,fopen()
返回NULL
並通過NULL
到fputs()
將導致訪問衝突。
+1檢查錯誤返回! – 2010-04-03 03:17:50
您是否正在檢查以確保文件已正確打開?
通常情況下,您需要超級用戶權限才能寫入/ var,所以這可能是您的問題。
我已經在評論回答了這個和一對夫婦的人都告訴你你做了什麼不對的答案,但我決定加入少許示例代碼錯誤檢查:
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);
}
現在你會看到如果你的文件沒有打開,它會描述爲什麼(在你的情況下,訪問被拒絕)出錯。您可以通過以下方式進行測試:1)用世界上可寫的替換文件名,如"/tmp/wiki.txt"
;或2)以特權sudo ./your_command_name
運行您的實用程序。
fopen(3)失敗。 scriptFile爲NULL,在嘗試寫入之前應檢查它。在Mac OS X中,/ var不是全球可寫的。 – 2010-04-03 03:15:57