簡體   English   中英

在 C 中使用 fget 時出現“分段錯誤:11”

[英]"Segmentation fault: 11" when using fgets in C

我正在 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;
}
if((file=fopen("~/.undersave","r"))){
}else{
   // all the code
}

這似乎是倒退。 它說,如果 fopen 成功,什么也不做; 如果失敗,則執行所有代碼。 這可能會導致另一個fopen也失敗,然后你fprintf到一個段錯誤的 null 文件指針。

它可能確實會失敗,因為在類 Unix 系統上~ -expansion 是 shell 的一個功能,並且不適用於直接使用fopenopen文件的程序。 如果要打開相對於主目錄的文件,請包含完整路徑,或使用getenv讀取HOME環境變量並在程序中構建路徑。 或者,更好的是,使文件名成為命令行參數; 那些 arguments 在您的程序看到它們之前由 shell 擴展,所以~擴展就可以了。

此外,您的printf("X")不是一個很好的診斷工具,因為到終端的 output 通常是緩沖的。 在打印新行或嘗試從標准輸入讀取或發生其他一些特殊情況之前,X 實際上不會被寫入屏幕。 所以我懷疑程序實際上比你想象的更晚崩潰,在fprintf而不是fgets上。 請參閱為什么 printf 在調用后不刷新,除非換行符在格式字符串中? 然后將fflush(stdout)放在你的m() printf中的 printf 之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM