【问题标题】:Question about writing and reading a 2D integer array to a text file关于将二维整数数组写入和读取到文本文件的问题
【发布时间】:2021-04-20 16:23:45
【问题描述】:

我想在我的代码中做两件事

1) 编写一个程序,将二维整数数组写入文本文件。 和

2) 编写第二个程序从文本文件中读取二维整数数组。第二个程序应该在屏幕上打印矩阵。另外要获取文件名,我应该使用命令行参数。 例如在 cmd 上的输出应该是这样的:

矩阵.txt

8 3 3 1

13 5 31 -8

9 9 0 42

这是我编写的代码。但是,只有错误消息“无法打开 matrix.txt”出现。我的代码有什么问题?

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

#define _CRT_SECURE_NO_WARNINGS
#define ROW 3
#define COL 4
#define FILE_NAME "matrix.txt"

void input_matrix(int matrix[ROW][COL], FILE*);

int main()
{
int Multiarray[ROW][COL];
int i, j;
FILE* fp;
fp = fopen_s(&fp, FILE_NAME, "r");

if (fp == NULL)
{
    fprintf(stderr, "Can't open %s\n", FILE_NAME);
    exit(EXIT_FAILURE);
}

else
{
    input_matrix(Multiarray, fp);

    for (i = 0; i < ROW; i++)
    {
        for (j = 0; j < COL; j++)
        {
            fprintf(fp, "%d ", Multiarray[i][j]);
        }
        fprintf(fp, "\n");
    }
}
//This part should print out the result of my input

close(fp);
return 0;
}

void input_matrix(int matrix[ROW][COL], FILE* fp)
{
   int i, j;
   fp = fopen_s(&fp, FILE_NAME, "w");

   for (i = 0; i < ROW; i++)
   {
       for (j = 0; j < COL; j++)
       {
           fscanf_s(fp, "%d", &matrix[i][j]);
           // I have already scanned all the element of my array
       }
   }
}

【问题讨论】:

  • 您正在打开文件进行阅读。你可能想在fopen中使用“rw”而不是“r”
  • Emanuel P) 我试过了,但调试器不起作用。
  • 我的猜测:matrix.txt 不是 mymatrix.txt。
  • Zilog80) 我的错误,但输出应该是 matrix.txt。我会解决的
  • 您使用相同的文件指针打开了相同的文件进行读写。

标签: c matrix cmd


【解决方案1】:

函数 fopen_s 成功返回 0。结果程序成功失败。

试试:

int ret = fopen_s(&fp, FILE_NAME, "r");

if (ret != 0)
{
    fprintf(stderr, "Can't open %s\n", FILE_NAME);
    exit(EXIT_FAILURE);
}

【讨论】:

  • 不幸的是,此消息出现:在 matrixreader.exe 中的 0x7763FEA5 (ntdll.dll) 处引发异常:0xC0000005:访问冲突写入位置 0x00000031。
  • @hong 尝试从 input_matrix() 中删除 fopen_s
猜你喜欢
  • 2013-03-11
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多