我正在用 C 撰寫一個命令列工具來控制 UNDERTALE 保存檔案(因為為什么不),每當我從用戶那里獲取輸入時,我都會遇到分段錯誤。
這是我的所有代碼:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#define KILOBYTE 1024
/* The 'm()' is so i know what line the fault happens on */
void m(void) {
printf("X");
}
int main(int argc, char**argv) {
FILE *file;
if (file = fopen("~/.undersave", "r")) {
// Do some code that I haven't written yet
}
else {
char path[KILOBYTE] = "";
printf("It seems that this is your fist time using UNDERSAVE.\nWe just need to go through some quick installation steps.\nWhere do you want your UNDERTALE save folder to be located? >>> ");
m();
fgets(path, KILOBYTE, stdin);
/*
The fault happens here, when it asks me,
i put in the input like normal, but
when I press enter, I get a fault before
it prints 'X'
*/
m();
mkdir(path, 0777);
m();
file = fopen("~/.undersave", "w");
m();
fprintf(file, "%s", path);
m();
fclose(file);
}
return 0;
}
uj5u.com熱心網友回復:
很可能兩個呼叫都fopen失敗了,因為在類 Unix 系統上~-expansion 是 shell 的一個特性,不適用于直接用fopen或打開檔案的程式open。如果要打開相對于主目錄的檔案,請包含完整路徑,或使用getenv讀取HOME環境變數并在程式中構建路徑。或者,更好的是,使檔案名成為命令列引數;這些引數在你的程式看到它們之前被 shell 擴展,所以~擴展會起作用。
所以fopenfor write 回傳 NULL,你沒有測驗它(一個更嚴重的錯誤)。然后您嘗試fprintf指向一個空檔案指標,這自然會崩潰。
此外,您的printf("X")診斷也不是很好,因為通常會緩沖到終端的輸出。在列印新行之前,或者直到您嘗試從 stdin 讀取資料,或者發生其他一些特殊情況之前,X 不會實際寫入螢屏。所以我懷疑程式實際上比你想象的更晚崩潰,fprintf而不是fgets. 請參閱為什么 printf 在呼叫后不會重繪 ,除非格式字串中有換行符?然后把fflush(stdout)后printf您的m()功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378642.html
