2016-02-14 82 views
2

當我使用導入到Xcode的文件運行此程序時,我在c = fgetc(ptr);行收到Thread 1: EXC_BAD_ACCESS (code=1 address=0x68)的錯誤。我不知道爲什麼fptr在它到達這一行時爲空。任何幫助將非常感謝。使用帶有Xcode的文件的問題c

#include <stdio.h> 
#define M 100 
#define N 100 
char array[M][N] = {0}; 
void readFile(); 
void findStartandEnd(); 
void mazeTraversal(); 
int m = 0; 
int n = 0; 
int start[2] = {0}; 
int end[2] = {0}; 

int main() { 
    readFile(); 
    //findStartandEnd(); 
    //mazeTraversal(); 
} 

void readFile() { 
    FILE *fptr; 
    char c; 
    char file_name[20]; 
    int i, j; 

    printf("Please enter the size of the MxN maze.\n"); 
    printf("Start with the M size then the N size follow each number by the return key.\n"); 
    scanf("%d", &m); 
    scanf("%d", &n); 
    printf("Type in the name of the file containing the Field\n"); 
    scanf("%s", file_name); 
    fptr = fopen(file_name, "r"); 
    for (i = 0; i < M && i < m; i++) 
     for (j = 0; j < N && j < n; j++) { 
      c = fgetc(fptr); 
      while (!((c == '1') || (c =='0'))) 
       c = fgetc(fptr); 
      array[i][j] = c; 
     } 
    fclose(fptr); 

    for (i = 0; i < M && i < m; i++) 
     for (j = 0; j < N && j < n; j++) { 
      if (j == 0) printf("\n"); 
      printf("%c ", array[i][j]); 
     } 
    printf("\n"); 
} 
+1

您是否檢查過驗證'fptr'是否有效?在取消引用可能是NULL指針之前,確實應該確保文件已成功打開。 –

+2

@ChadBrown:你爲什麼回滾編輯? – chqrlie

+0

'void readFile();'等不是有效的原型,並使用不贊成使用的語法。 – Olaf

回答

1

你不考,如果scanf正確解析字符串爲file_name。你甚至不保護file_name從潛在的緩衝區溢出與scanf("%19s", file_name);

而且,你不考fopen是否成功在打開文件。 fptr可能是NULL由於許多可能的原因,您必須測試並優雅地失敗。

請注意,scanf將在第一個單詞後的第一個空白字符處停止。帶有嵌入空格的文件名不能用此方法輸入。

還要注意c應該定義爲int,而不是char正確測試文件由fgetc()返回不適合在charEOF結束。

您還應該使用大括號圍繞由for循環所表彰的非重要語句。它們不是絕對必要的,但它會在稍後修改代碼時避免愚蠢的錯誤。