【问题标题】:Read a file character by character and pass them to an array in C逐个字符读取文件并将它们传递给 C 中的数组
【发布时间】:2020-10-17 11:26:40
【问题描述】:

我必须从文件中解析一个矩阵,其中第一行字符是行数,列数是矩阵值。


文件包含:

3 3
R R B
B G G
G B R

我写了下面的代码,但是它崩溃了。

char** readMatrix(FILE *file) {
    char *array;
    int el = 0;
    while (fscanf_s(file, "%s", array) != EOF) {
    array[el] = array;
    el++;
    }
    const int n = array[0] - '0', m = array[1] - '0';
    char** matrix = malloc(n * sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        matrix[i] = malloc(m * sizeof(char));
    }
    int k = 2;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            matrix[i][j] = array[k];
            ++k;
        }
    }
    return matrix;
}

不同文件的矩阵大小不同。如何在不知道大小的情况下声明一个 char 数组?

【问题讨论】:

  • 根据需要使用realloc() 发光阵列。
  • 需要动态分配,或者使用变长数组。但是目前你只是在使用array 而不为它设置任何值,这是未定义的行为。将编译器的警告设置为最大。
  • array[el] = array 这是在做什么? array 不仅是一个未初始化的指针,因此很可能是导致崩溃的原因,而且存储对数组本身的引用也很奇怪。改为使用 %d 解析整数。
  • array[el] = array -> 我正在尝试将输入值分配给数组元素。

标签: c file matrix 2d


【解决方案1】:

首先您需要检查您的 FILE 是否不为 NULL(这可能导致崩溃)

if ( file == NULL ) {
    printf("Error"); 
    exit(1);
}

那么你需要确保你的 FILE 的指针指向文件的开头:

fseek(file, 0, SEEK_SET);

如果你的规则是:'第一行总是包含两个用空格分隔的正整数,并在第二个 uint 之后结束该行',那么你可以像这样阅读它们:

int dim_x = 0, dim_y = 0 ;
fscanf(file, "%d %d\n", &dim_x, &dim_y);
if(dim_x <= 0 || dim_y <= 0){
    printf("Impossible to get correct the correct dimensions");
    exit(1);
}

然后您可以逐行读取文件以获得正确的数据。

读取文件有很多变化。假设您的文件的任何数据都是由 1 个空格或 1 个反线间隔的单个字符,您可以像这样循环:

    char ** matrix = (char**)malloc(sizeof(char*) * nbr_y);

    for(int line = 0 ; line < nbr_y ; line ++){
        matrix[line] = (char*)malloc(sizeof(char) * nbr_x); 
        for(int data_x_index = 0 ; data_x_index < nbr_x ; data_x_index ++){
            fscanf(f, "%c", &matrix[line][data_x_index]); //Read and stock the character direclty in the matrix
            fseek(f, 1, SEEK_CUR); // Go to the next character to read
        }
    }

    for(int i = 0 ; i < nbr_y ; i ++){
        for(int j = 0 ; j < nbr_x ; j ++){
            printf("%c ", matrix[i][j]);
        }
        printf("\n");
    }
}

注意:此版本不检查文本是否格式正确以及尺寸是否正确!

【讨论】:

  • 它只读取矩阵的第一行字符。
  • 在 .txt 中的换行符之前打印一个空格
  • 你可以尝试这样调试:for(int data_x_index = 0 ; data_x_index &lt; nbr_x ; data_x_index ++){ fscanf(f, "%c", &amp;matrix[line][data_x_index]); //Read and stock the character direclty in the matrix printf("Character read at %d, %d : %d\n", line, data_x_index, matrix[line][data_x_index]); fseek(f, 1, SEEK_CUR); // Go to the next character to read }
猜你喜欢
  • 2018-12-14
  • 2016-12-15
  • 1970-01-01
  • 2021-06-14
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多