从文件中读取值并将其存储在2D矩阵中

时间:2018-12-26 18:34:37

标签: c file-handling file-read

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

#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;
}

1 个答案:

答案 0 :(得分:4)

C中的数组始于0,结束于(array_size - 1)

当您访问数组外部的内存时,很可能遇到分段错误。

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

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

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

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

请注意,我将关系运算符分别从<=>=更改为<>

此外,您可能需要完全初始化数组。如果未初始化数组,则可能会打印奇数值。 (@风向标)。

但是,为了最好地确定是否确实如此,我们需要file.txtfile1.txt

相关问题