读取文件并使用 c 将行保存在数组中

Read a file and save the lines in an array with c

我正在尝试读取给定的 file 并将其行写入 array。起初,我不是 dynamically allocating 将存储 file 行的变量(迷宫)。这是我的 code 直到现在。

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

int main(void)
{
 
    char c, maze[300][300], buffer[1000] = {'[=10=]'};
    int ch = 0, column, row, columns = 0, rows = 0;
    
    FILE* file = fopen("boards/0.txt", "r+");

    if ( file )
    {
        while( fgets(buffer, sizeof(buffer), file) != NULL)
            rows+=1;
    }
    // rows will count the number of rows 
    else
    {
        printf("There's no such file.\n");
        exit(1);
    }
    // and  columns  will count the number of columns
    columns = (strlen(buffer) - 1);

    // write the content file into an matriz
    for (row = 0; row < rows ; row++)
    {
  
        for (column = 0; column < columns; column++)
        {
          
            if(fscanf(file, "%c", &maze[row][column]) != 1)
                exit(1);

        }
        
    }

    fclose(file);
    // print rows
    for (row = 0; row < rows; row++)
    {
        
        for (column = 0; column < columns; column++)
        {
            printf("%c",maze[row][column]);
            

        }
        
    }

    
    return 0;

}

这是输入文件:

....*.....................
..........................
........*........*........
.....*....................
...............*....*.....
..*.......*...............
............*.............
..........................
..............*...........
..................*.......
..*.......*......*........
....*..*..................
...**.....................
..........*...............
....................*.....
..........................
....**....................
......................*...

输出应该是一样的,但是没有任何反应。我知道我应该 dynamically allocate array,但我不确定如何将它放入代码中以使其工作。

您的解决方案的主要问题是您在完成第一次读取后没有重置文件位置。 您应该在第二次读取之前使用 fseek(file, SEEK_SET, 0)

另一个问题是您将 newline 个带有 fscanf 的字符读入一个迷宫位置,我想您不希望那样:)

您可以一次完成此过程:

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

int main(void)
{
    char maze[300][300] = { 0 };
    int column = 0, row = 0, columns = 0, rows = 0;

    FILE* file = fopen("boards/0.txt", "r");
    if (file) {
        while (fgets(&maze[rows][0], 300, file) != NULL) {
            rows++;
        }

        columns = strlen(&maze[0][0]) - 1;
    } else {
        printf("There's no such file.\n");
        return 1;
    }

    fclose(file);
    // print rows
    for (row = 0; row < rows; row++) {
        for (column = 0; column < columns; column++) {
            printf("%c", maze[row][column]);
        }
        printf("\n");
    }

    return 0;
}