首页 > 解决方案 > 创建一个包含整数矩阵的文件。将第一个负元素的行元素替换为具有相同数字的列元素

问题描述

任务:
创建一个包含A维度整数矩阵的文件m*m。在不将矩阵读入内存的情况下,将具有第一个负元素的行元素替换为具有相同编号的列元素。
逐行打印原始矩阵和生成的矩阵。它向我输出相同的矩阵。我需要用列元素替换行元素。

我对矩阵创建功能没有任何问题。但问题在于read_k功能。

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

// creating a binary file with the name,
// containing N*N integers.
void create_file(char *name, int n)
{
    FILE *f = fopen(name,"wb");
    if (f==NULL) 
    {
        printf("file creation error \n");
        system("pause");
        return ;
    }
    // write the variable n to the file
    fwrite(&n,sizeof(n),1,f);
    int i;
    // write the elements of the square matrix to the file.
    for( i=0;i<n*n;i++)
    {
        int z = rand()%200-rand()%100;
        fwrite(&z,sizeof(int),1,f);
    }
    fclose(f);
}

// function for reading a file with the name.
void read_file(char *name)
{
    int m;
    FILE *f = fopen(name,"rb");
    if (f==NULL) 
    {
        printf("file not found \n");
        system("pause");
        return ;
    }
    
    int i = 0;
    // reading the dimension of the matrix..
    int z;
    fread(&m,sizeof(int),1,f);
    //reading the entire matrix and displaying it on the screen..
    while(!feof(f))
    {
        if (i>=m&&i%m==0)
            printf("\n");
        if(fread(&z,sizeof(int),1,f)!=1) 
            break;
        printf("%8d",z);
        i++;
    }
    fclose(f);
}

void read_k(char *name, int n)
{
    char *A[30];
    int m;
    FILE *f = fopen(name,"rb");
    if (f==NULL) 
    {
        printf("file not found \n");
        system("pause");
        return ;
    }
    
    int z;
    int i,j;
    
    fread(&m,sizeof(int),1,f);
    
    for( i=0;i<m;i++)
    {
        if(i<0)
        { 
            A[i][j]=A[j][i];
            j++;
        }
    }
    
    while(!feof(f))
    {
        if (i>=m&&i%m==0)
            printf("\n");
        if(fread(&z,sizeof(int),1,f)!=1) break;
            printf("%8d",z);
        i++;
    }
    fclose(f);
}

int main(int argc, char *argv[])
{
    char Fname[30];
    int n,m;
    printf("file name: ");
    scanf("%s",Fname);
    printf("enter the number of rows in the matrix: ");
    scanf("%d",&n);
    
    create_file(Fname,n);
    printf("matrix : \n");
    read_file(Fname);
    printf("the new matrix %d \n",m);
    read_k(Fname,n);
    system("pause");
    return 0;
} 

标签: arrayscfilematrix

解决方案


推荐阅读