如何读取文本文件图像并将其保存到阵列?

时间:2018-03-25 17:34:02

标签: c arrays 2d

我必须编写一个程序,该程序读入文本二进制图像1和0,然后根据用户的选择对图像执行各种操作。我相信我对大部分程序都很好,我能够在文件中读取并显示它。 为了继续,我需要将图像保存到2D阵列,这就是我所困扰的。

下面是我整个节目的一小部分,因为其余部分目前正在运作,这是我想弄清楚的一点,但在继续搜索和视频之后,我不能为我的生活想出这个或者在哪里我错了。

#define N 50
int imageArray [N][N];
int row, col;
int value;
char filename[30];
FILE *ptr_file;
printf("Enter the full name of the input file: ");
scanf("%s", filename);

ptr_file = fopen(filename, "r");

for(row = 0; row < N; row++){
    for(col = 0; col < N; col++){
        fscanf(ptr_file, "%d", &value);
        imageArray[row][col] = value;
    }

}

for(row = 0; row < N; row++){
    for(col = 0; col < N; col++){
        printf("%d", imageArray[N][N]);
    }
    printf("\n");
}

我试图保存到2D阵列的图像都是50x50并包含在txt文件中。

上面的代码目前输出所有0。图像的背景由0组成,而图像本身由1组成。

以下是我想要保存到阵列的超小版本,想象它是50x50!由于某种原因,我无法在此处粘贴完整图像,因为它重新格式化了它。它应该给出一个想法。

0000000
0001000
0011100
0111110
0011100
0001000
0000000

提前感谢阅读帖子!

1 个答案:

答案 0 :(得分:0)

您的代码存在两个问题。

  1. 正如Mike P所说,你应该使用带有fscanf()的“%1d”,否则每个fscanf()调用都将读取整行,因为它将继续读取,直到第一个数字字符系列的末尾为“ %d”。

  2. 您的打印循环正在打印imageArray[N][N]而不是imageArray[row][col]

  3. 实现了这两个修复程序后,我得到了按预期运行的代码。

    int imageArray [N][N];
    int row, col;
    int value;
    char filename[30];
    FILE *ptr_file;
    printf("Enter the full name of the input file: ");
    scanf("%s", filename);
    
    ptr_file = fopen(filename, "r");
    
    for(row = 0; row < N; row++){
        for(col = 0; col < N; col++){
            fscanf(ptr_file, "%1d", &value);
            imageArray[row][col] = value;
            printf("%d %d\n", row, col);
        }
    
    }
    
    for(row = 0; row < N; row++){
        for(col = 0; col < N; col++){
            printf("%d", imageArray[row][col]);
        }
        printf("\n");
    }
    

    作为补充说明,您应该检查fscanf()的返回以确保调用成功。如果您使用原始代码执行此操作,它将为您提供第一个错误位置的良好提示。它也可用于检测无效的输入文件。

相关问题