2017-10-17 276 views
1

我有一個名爲input1.txt的文件,它是一個數字和一些字母的矩陣。我試圖讀取並將其存儲在二維數組中,以便每個章程都是1個單元格。這是我的文本文件:C將文件讀入二維數組

1111S11110 
0000010001 
110100010d 
t001111110 
0100000001 
0111111101 
1111111101 
00000D01T1 
0111110001 
0000E01110 

這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


// Function for finding the array length 
int numOfLines(FILE *const mazeFile){ 
    int c, count; 
    count = 0; 
    for(;;){ 
     c = fgetc(mazeFile); 
     if(c == EOF || c == '\n') 
      break; 
     ++count; 
    } 
    return count; 
} 

// Main Function 
int main(int argc, char **argv) 
{ 
    // Opening the Matrix File 
    FILE *mazeFile; 
    mazeFile = fopen("input1.txt", "r"); 
    if(mazeFile == NULL) 
     return 1; 
    int matrixSize = numOfLines(mazeFile); 

    // Reading text file into 2D array 
    int i,j; 
    char mazeArray [matrixSize][matrixSize]; 

    for(i=0;i<matrixSize;i++){ 
      for(j=0;j<matrixSize;j++){ 
       fscanf(mazeFile,"%c", &mazeArray[i][j]); 
      } 
    } 

    for(i=0;i<matrixSize;i++){ 
     for(j=0;j<matrixSize;j++){ 
      printf("%c",mazeArray[i][j]); 
     } 
    } 

    fclose(mazeFile); 
    return 0; 
} 

但是我的控制檯輸出就是這樣,當我打印出來:

0000010001 
110100010d 
t001111110 
0100000001 
0111111101 
1111111101 
00000D01T1 
0111110001 
[email protected] 

看來它不讀第一行,但在索引方面,我認爲它是好的。我是新來的C.請任何人請幫助。提前感謝。

+1

您的'numOfLines'是一個用詞不當,它計數第一行中的字符數。因此,讀它們!你爲什麼認爲如果你繼續閱讀,你會從頭開始重新開始?魔法?試試['rewind()'](https://linux.die.net/man/3/rewind)。 –

+1

您的'numOfLines()'函數將文件讀取到最後。如果你想重新閱讀它,你需要回到開始(這可以用於普通文件,但不適用於其他可能的流類型)。 –

+1

@JohnBollinger它**不會**讀到最後,這增加了這個代碼的混亂...... –

回答

1

這裏有幾個問題:

numOfLines功能是錯誤的。這是更正後的版本;它實際上會計算行數並將文件指針重置爲文件的開頭。

您的版本只計算第一行中的字符數(恰好爲10,因此該值似乎正確),並且它沒有將文件指針重置爲文件開頭(因此第一行在輸出中丟失)。

int numOfLines(FILE *mazeFile) { // no const here BTW !! 
    int c, count; 
    count = 0; 
    for (;;) { 
    c = fgetc(mazeFile); 
    if (c == EOF) 
     break;   // enf of file => we quit 

    if (c == '\n') 
     ++count;  // end of line => increment line counter 
    } 
    rewind(mazeFile); 

    return count+1; 
} 

然後你忘記吸收\n字符在每行的末尾。該\n位於文件每行的末尾,但即使您不想將其存儲在二維數組中,也需要閱讀該文件。

for (i = 0; i<matrixSize; i++) { 
    for (j = 0; j<matrixSize; j++) { 
     fscanf(mazeFile, "%c", &mazeArray[i][j]); 
    } 

    char eol;       // dummy variable 
    fscanf(mazeFile, "%c", &eol);  // read \n character 
    } 

最後你需要打印\n由於上述原因。

for (i = 0; i<matrixSize; i++) { 
    for (j = 0; j<matrixSize; j++) { 
    printf("%c", mazeArray[i][j]); 
    } 

    putc('\n', stdout);     // print \n 
} 
+0

感謝您幫助我看到我的錯誤:),那真是太好了。 –

+1

@HabilGanbarli不客氣。對於明確的問題,您幾乎總能得到一個快速而明確的答案。 –