c - 从文件中读取值并将其存储在二维矩阵中

标签 c file-handling file-read

我正在尝试从一个文件中读取值,然后在一些操作后写入另一个文件。这里面临一个小问题,因为我也在尝试将值保存在二维数组中并显示它。我的文件读取和文件写入显示正确的结果,但我的程序在显示矩阵部分时抛出异常。

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

#ifndef NULL
#define NULL   ((void *) 0)
#endif

int main(void)
{
    FILE *file  = NULL; //for file read
    FILE *fptr  = NULL; //for file write

    int mat[182][274];

    // code to read and display number from file
    // open file for reading
    file = fopen("file.txt", "r");
    fptr = fopen("file1.txt", "w");
    int i = 0,j=0;

    fscanf (file, "%d", &i);    
    while (!feof (file))
    {
        symbol = fgetc(file);

        if (symbol == '\n' || feof(file))
        {
            fprintf (fptr,"\n");
            printf("\n");
        }
        else{
            j=255-i;

            mat[i][j]=j;

            fprintf (fptr,"%d ", j);
            fprintf (fptr," ");
            printf ("%d ", j);
        }

        fscanf (file, "%d", &i);

   }
   fclose (file);
   fclose (fptr);


   //Facing issue in this part
   int k;
   int l;
   for (k=0;k<=182;k++)
   {

       for(l=0;l<=274;l++)
       {

           printf("%d ", mat[k][l]);
       }
   }

   return 0;
}

最佳答案

C 中的数组从 0 开始结束于 (array_size - 1) .

当您访问阵列外部的内存时,您很可能会遇到段错误。

要解决此问题,请更改以下行:

 for (k=0;k<182;k++)
 {

  for(l=0;l<274;l++)
  {

      printf("%d ", mat[k][l]);
  }
 }

请注意,我更改了 <= 中的关系运算符和 >=<> , 分别。

除此之外,您可能需要完全初始化您的阵列。如果数组未初始化,可能会打印奇数。 (@Weather Vane)。

但是,为了最好地确定是否是这种情况,我们需要 file.txtfile1.txt .

关于c - 从文件中读取值并将其存储在二维矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53935788/

相关文章:

c - 关于交叉编译的 c 中内置函数的警告

c - 打印星形或 "X"图案

perl - Perl 中 '>>' 和 '>' 的区别

javascript - PHP 搜索文件中不匹配的行

java - 用java读取html文件

javascript - 有没有办法读取服务器上的文件而无需在 Node js中下载?

python - 如何更改 JSON 中包含引号的文本?

c - 用execv执行shell程序

c - 使用 openssl 进行 Base64 解码的一个非常奇怪的错误

Java格式化程序-设置文件目录