在C语言中将2-D数组保存到二进制文件中

huangapple go评论55阅读模式
英文:

Saving of 2-D array to the binary file in C language

问题

我试图将一个二维整数数组保存到二进制文件中。问题是只有二维数组的第一行被保存了。以下是我附上的输出,您将更好地理解问题。提前感谢您的帮助。

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

#define N_MAX 100

// 函数声明
int readMatrix(FILE *fp, int matrix[N_MAX][N_MAX]);
void printMatrix(int matrix[N_MAX][N_MAX], int size);
void switchMax(int matrix[N_MAX][N_MAX], int size);
int avg(int matrix[N_MAX][N_MAX], int size);
int sumDown(int matrix[N_MAX][N_MAX], int size);
int sumUp(int matrix[N_MAX][N_MAX], int size);
void sortMainDiagonal(int matrix[N_MAX][N_MAX], int size);

int main()
{
    int size, matrix[N_MAX][N_MAX], test[N_MAX][N_MAX];
    FILE *fp;
    fp = fopen("input.txt", "r");

    if (fp != NULL)
    {
        size = readMatrix(fp, matrix);
        fclose(fp);

        switchMax(matrix, size);
        avg(matrix, size);
        sortMainDiagonal(matrix, size);

        printf("\n原始矩阵: \n");
        printMatrix(matrix, size);
        
        // 保存到二进制文件
        fp = fopen("output.bin", "w");
        if (fp != NULL)
        {
            fwrite(matrix, sizeof(int), size*size, fp);
            fclose(fp);
        } else {
            printf("错误 #e2");
        }

        // 从二进制文件读取
        fp = fopen("output.bin", "r");
        if (fp != NULL)
        {
            fread(test, sizeof(int), size*size, fp);
            fclose(fp);

            printf("\n从文件中读取的矩阵: \n");
            printMatrix(test, size);
        } else {
            printf("错误 #e3");
        }
    } else {
        printf("错误 #e1");
    }
}

// 函数定义
int readMatrix(FILE *fp, int matrix[N_MAX][N_MAX])
{
    int size = 0;
    fscanf(fp, "%d", &size);
    for (int i = 0; i < size; i++)
        for (int j = 0; j < size; j++)
            fscanf(fp, "%d", &matrix[i][j]);
    
    return size;
}

void printMatrix(int matrix[N_MAX][N_MAX], int size)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

void switchMax(int matrix[N_MAX][N_MAX], int size)
{
    int max = 0, row = 0;
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            if (matrix[j][i] > max)
            {
                max = matrix[j][i];
                row = j;
            }
        }
        matrix[row][i] = matrix[i][i];
        matrix[i][i] = max;
        max = 0;
    }
}

int avg(int matrix[N_MAX][N_MAX], int size)
{
    int avg;
    avg = (sumDown(matrix, size) + sumUp(matrix, size)) / 2;
    matrix[size-1][size-1] = avg;
    return avg;
}

int sumDown(int matrix[N_MAX][N_MAX], int size)
{
    int sum = 0;
    for (int i = 1; i < size; i++)
        for (int j = 0; j < i; j++)
            sum += matrix[i][j];

    return sum;
}

int sumUp(int matrix[N_MAX][N_MAX], int size)
{
    int sum = 0;
    for (int i = 0; i < size-1; i++)
        for (int j = i+1; j < size; j++)
            sum += matrix[i][j];

    return sum;
}

void sortMainDiagonal(int matrix[N_MAX][N_MAX], int size)
{
    int temp;
    for (int i = 0; i < size-1; i++)
    {
        for (int j = 0; j < (size-1-i); j++)
        {
            if (matrix[j][j] > matrix[j+1][j+1])
            {
                temp = matrix[j][j];
                matrix[j][j] = matrix[j+1][j+1];
                matrix[j+1][j+1] = temp;
            }
        }
    }
}

'printMatrix' 函数的输出截图:
点击查看

文件 'input.txt' 内容:

4
5 6 1 8
1 20 3 4
9 0 11 12
13 4 15 1
英文:

I'm trying to save a 2-D array of integers to a binary file. The problem is that only the first row of the 2-D array is ​​saved. Below I have attached the outputs from which you will better understand the problem. Thanks in advance for the help.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#define N_MAX 100
// Declaration of functions
int readMatrix(FILE *fp, int matrix[N_MAX][N_MAX]);
void printMatrix(int matrix[N_MAX][N_MAX], int size);
void switchMax(int matrix[N_MAX][N_MAX], int size);
int avg(int matrix[N_MAX][N_MAX], int size);
int sumDown(int matrix[N_MAX][N_MAX], int size);
int sumUp(int matrix[N_MAX][N_MAX], int size);
void sortMainDiagonal(int matrix[N_MAX][N_MAX], int size);
int main()
{
int size, matrix[N_MAX][N_MAX], test[N_MAX][N_MAX];
FILE *fp;
fp = fopen(&quot;input.txt&quot;, &quot;r&quot;);
if (fp != NULL)
{
size = readMatrix(fp, matrix);
fclose(fp);
switchMax(matrix, size);
avg(matrix, size);
sortMainDiagonal(matrix, size);
printf(&quot;\nOriginal matrix: \n&quot;);
printMatrix(matrix, size);
// SAVE ON BINARY FILE
fp = fopen(&quot;output.bin&quot;, &quot;w&quot;);
if (fp != NULL)
{
fwrite(matrix, sizeof(int), size*size, fp);
fclose(fp);
} else {
printf(&quot;Error #e2&quot;);
}
// READ FROM BINARY FILE
fp = fopen(&quot;output.bin&quot;, &quot;r&quot;);
if (fp != NULL)
{
fread(test, sizeof(int), size*size, fp);
fclose(fp);
printf(&quot;\nMatrix from file: \n&quot;);
printMatrix(test, size);
} else {
printf(&quot;Error #e3&quot;);
}
} else {
printf(&quot;Errore #e1&quot;);
}
}
// Definition of functions
int readMatrix(FILE *fp, int matrix[N_MAX][N_MAX])
{
int size = 0;
fscanf(fp, &quot;%d&quot;, &amp;size);
for (int i = 0; i &lt; size; i++)
for (int j = 0; j &lt; size; j++)
fscanf(fp, &quot;%d&quot;, &amp;matrix[i][j]);
return size;
}
void printMatrix(int matrix[N_MAX][N_MAX], int size)
{
for (int i = 0; i &lt; size; i++)
{
for (int j = 0; j &lt; size; j++)
{
printf(&quot;%d &quot;, matrix[i][j]);
}
printf(&quot;\n&quot;);
}
}
void switchMax(int matrix[N_MAX][N_MAX], int size)
{
int max = 0, row = 0;
for (int i = 0; i &lt; size; i++)
{
for (int j = 0; j &lt; size; j++)
{
if (matrix[j][i] &gt; max)
{
max = matrix[j][i];
row = j;
}
}
matrix[row][i] = matrix[i][i];
matrix[i][i] = max;
max = 0;
}
}
int avg(int matrix[N_MAX][N_MAX], int size)
{
int avg;
avg = (sumDown(matrix, size) + sumUp(matrix, size)) / 2;
matrix[size-1][size-1] = avg;
return avg;
}
int sumDown(int matrix[N_MAX][N_MAX], int size)
{
int sum = 0;
for (int i = 1; i &lt; size; i++)
for (int j = 0; j &lt; i; j++)
sum += matrix[i][j];
return sum;
}
int sumUp(int matrix[N_MAX][N_MAX], int size)
{
int sum = 0;
for (int i = 0; i &lt; size-1; i++)
for (int j = i+1; j &lt; size; j++)
sum += matrix[i][j];
return sum;
}
void sortMainDiagonal(int matrix[N_MAX][N_MAX], int size)
{
int temp;
for (int i = 0; i &lt; size-1; i++)
{
for (int j = 0; j &lt; (size-1-i); j++)
{
if (matrix[j][j] &gt; matrix[j+1][j+1])
{
temp = matrix[j][j];
matrix[j][j] = matrix[j+1][j+1];
matrix[j+1][j+1] = temp;
}
}
}
}

Screenshot of outputs from 'printMatrix' function:
click

File 'input.txt':

4
5 6 1 8
1 20 3 4
9 0 11 12
13 4 15 1

答案1

得分: 1

你没有显示N_MAX的值,但你的图像(应该是问题中的文本!)显示一个4x4的矩阵。将来,请创建一个MCVE(Minimal, Complete, Verifiable Example)。

然而,让我们假设N_MAX是16或更多(但dim是4)。那么你的代码在写入矩阵时写了很多零。并且跳过了其他数据。

你的矩阵看起来像这样:

13  6   1   8   0  0  0  0  0  0  0  0  0  0  0  0
1   15  3   4   0  0  0  0  0  0  0  0  0  0  0  0
9   0   20  1   0  0  0  0  0  0  0  0  0  0  0  0
5   4   11  26  0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0

fwrite()写入了读取的前16个整数值。正如你演示的那样,其中有12个是零。

要写入子数组,你需要分别写入矩阵的前dim行的dim个条目。

for (size_t i = 0; i < dim; i++)
{
    if (fwrite(matrix[i], sizeof(int), dim, fp) != dim)
        err_syserr("矩阵的第%zu行写入错误\n", i);
}

fread()代码也类似。

函数err_syserr()在退出之前格式化并打印给定的错误消息和与errno关联的系统错误消息,退出时返回非零(失败)状态。在我的GitHub SOQ(Stack Overflow Questions)存储库中的文件stderr.cstderr.h中提供了一套全面的错误报告函数,位于src/libsoq子目录中。

英文:

You don't show the value for N_MAX, but your image (which should be text in the question!) shows a 4x4 matrix. In future, please create an MCVE (Minimal, Complete, Verifiable Example).

However, let's suppose N_MAX is 16 or more (but that dim is 4). Then your code to write the matrix is writing a lot of zeroes. And skipping the other data.

Your matrix looks like:

13  6   1   8   0  0  0  0  0  0  0  0  0  0  0  0
1   15  3   4   0  0  0  0  0  0  0  0  0  0  0  0
9   0   20  1   0  0  0  0  0  0  0  0  0  0  0  0
5   4   11  26  0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0
0   0   0   0   0  0  0  0  0  0  0  0  0  0  0  0

And the fwrite() writes the first 16 integer values reading across. As you demonstrated, 12 of those are zeros.

To write a sub-array, you'll have to write the dim entries of each of the matrix's first dim rows separately.

for (size_t i = 0; i &lt; dim; i++)
{
if (fwrite(matrix[i], sizeof(int), dim, fp) != dim)
err_syserr(&quot;short write on row %zu of matrix\n&quot;, i);
}

And similarly with the fread() code.

<sup>
The function err_syserr() formats and prints the given error message and the system error message associated with errno before exiting with a non-zero (failure) status. A comprehensive suite of error reporting functions is available in my SOQ (Stack Overflow Questions) repository on GitHub as files stderr.c and stderr.h in the src/libsoq sub-directory.*
</sup>

huangapple
  • 本文由 发表于 2023年1月8日 23:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定