【问题标题】:How do I read binary data from a text file and store it in a 2D array in C如何从文本文件中读取二进制数据并将其存储在 C 中的二维数组中
【发布时间】:2024-01-08 11:11:01
【问题描述】:

我有一个看起来像这样的文本文件 (H.txt):

1 0 1 1 0 1
0 0 1 1 0 0
0 0 0 1 0 0
1 1 1 0 0 0

我需要将此文本文件读入一个名为 H 的二维数组。文本文件的大小可以在长度和宽度上发生变化(即,二进制数据的行数和列数可能比我上面的示例多) .

这是我目前所拥有的:

#import <stdio.h>

int main()
{

    int m = 4;
    int n = 6;
    int H[m][n];

    FILE *ptr_file;
    char buf[1000];

    ptr_file = fopen("H.txt", "r");
    if (!ptr_file)
        return 1;

    fscanf(ptr_file,"%d",H);

    fclose(ptr_file);
    return 0;
}

任何帮助将不胜感激。

【问题讨论】:

  • 是什么阻止你继续?
  • 你需要使用循环,两个嵌套的 for 循环可能是最简单直观的。你还没学会用 for 循环遍历数组吗?

标签: c arrays scanf


【解决方案1】:

喜欢这个

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

int getRows(FILE *fp){
    int ch, rows = 0, notTop = 0;
    while((ch = getc(fp))!= EOF){
        if(ch == '\n'){
            ++rows;
            notTop = 0;
        } else
            notTop = 1;
    }
    if(notTop)
        ++rows;
    rewind(fp);
    return rows;
}

int getCols(FILE *fp){
    int ch, cols = 0, preSpace = 1;
    while((ch = getc(fp))!= EOF && ch != '\n'){
        if(isspace(ch)){
            preSpace = 1;
        } else {
            if(preSpace)
                ++cols;
            preSpace = 0;
        }
    }
    rewind(fp);
    return cols;
}

int main(void){
    int rows, cols;
    FILE *fp = fopen("H.txt", "r");
    if (!fp){
        perror("can't open H.txt\n");
        return EXIT_FAILURE;
    }
    rows = getRows(fp);
    cols = getCols(fp);
    int (*H)[cols] = malloc(sizeof(int[rows][cols]));
    if(!H){
        perror("fail malloc\n");
        exit(EXIT_FAILURE);
    }
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            if(EOF==fscanf(fp, "%d", &H[r][c])){
                fprintf(stderr, "The data is insufficient.\n");
                free(H);
                exit(EXIT_FAILURE);
            }
        }
    }
    fclose(fp);
    //test print
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            printf("%d ", H[r][c]);
        }
        puts("");
    }

    free(H);
    return 0;
}

【讨论】:

    【解决方案2】:

    有很多方法可以解决您的问题。一种非常简单的方法是有两个循环,一个嵌套在另一个循环中。行的外部和列的内部。在内部循环中,您读取一个数字并将其存储到矩阵的正确位置。

    【讨论】:

      最近更新 更多