You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言方阵偶数元素文件读写功能异常求助

问题:方阵偶数元素写入文件后无法正确读取

我正在进行期末备考作业,需求是将n阶方阵中的偶数元素写入matran.txt文件,随后读取该文件并显示内容。目前写入函数infile运行正常,但读取函数DocTep存在异常:设置循环上限为n或100时,均无法正确读取全部偶数元素(比如输入n=3时,文件中有4个偶数,但读取结果不符合预期)。

完整代码如下:

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

void nhapmt (int **p,int n)
{
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      printf("a[%d][%d] = ", i, j);
      scanf("%d", &p[i][j]);
    }
  }
}

void inmt (int **p,int n)
{
    for (int i=0;i<n;i++)
    {
    printf ("\n");
    for (int j=0;j<n;j++)
    {
        printf ("%d\t",p[i][j]);
    }
}
}

void tongcheo(int **p,int n)
{
    int sum=0;
    for (int i=0;i<n;i++)
    {
        sum += p[i][i];
    }   
    printf ("\nTong cac so tren duong cheo chinh la: %d",sum);
}

void tongh(int **p,int n,int h)
{
    int sum=0;
    for (int i=0;i<n;i++)
    {
        sum += p[i][h];
    }   
    printf ("Tong cot %d la: %d",h,sum);
}

void infile(int **p,int n)
{
    bool a=false;
    FILE *f=fopen("matran.txt","w");
    if (f==NULL)
    {
        printf ("\nLoi file.");
        exit(1);
    }
      for (int i = 0; i < n; i++) 
      for (int j = 0; j < n; j++) {
        if ((p[i][j]) % 2 == 0) {
        fprintf (f,"%d\t",p[i][j]);
        a=true;
    }
    }   
    if (a) printf ("\nFile da duoc ghi tai ./matran.txt");
    else printf ("\nKhong co so chan trong ma tran");

}


void DocTep(int **p, int n) {
    int *ptr=(int*)malloc(100*sizeof(int));
  FILE *f = fopen("matran.txt", "r");
  if (f == NULL) {
    printf("\nLoi file.");
    exit (1);
  }
//    fscanf(f,"%d",&ptr[0]);
  for (int i = 0; i < n; i++) {
        fscanf(f, "%d ",ptr[i]);
  }

    fclose(f);
    printf ("\n");
    for (int i = 0; i < n; i++) {
        printf ("%d\t",ptr[i]);
}
}

int main()
{
    int **p,n,h;
    printf ("Hay nhap vao n: ");
    scanf("%d",&n);
    p=(int**)malloc(n*sizeof(int*));
    for (int i=0;i<n;i++){
    p[i]=(int*)malloc(n*sizeof(int));
    }
    nhapmt(p,n);
    inmt(p,n);
    tongcheo(p,n);
    printf ("\nHay nhap vao h: ");
    scanf("%d",&h); 
    tongh(p,n,h);
    infile (p,n);
    DocTep(p,n);
    free(p);
    return 0;
}

输入示例:n=3,矩阵含元素2、4、6、8,matran.txt内容为2 4 6 8,期望输出为2 4 6 8,但当前读取函数无法实现。


问题分析

  • 循环上限错误:DocTep函数中用方阵阶数n作为读取循环的次数,但n和文件中偶数元素的数量无关(比如n=3时,偶数数量可能是4),导致只能读取前n个元素,遗漏剩余内容。
  • 格式与内存问题:fscanf("%d ", ptr[i])的空格虽能匹配空白,但更稳妥的是用"%d";且原函数未释放ptr的内存,会造成内存泄漏。
  • 缺乏数量记录:写入文件时未记录偶数的总数量,读取时无法准确知道需要读取多少个元素。

解决方案

方案1:读取至文件结束(简单直接)

修改DocTep函数,无需依赖原方阵参数,直接读取文件中所有整数直到文件结束:

void DocTep() {
    int *ptr = (int*)malloc(100*sizeof(int));
    FILE *f = fopen("matran.txt", "r");
    if (f == NULL) {
        printf("\nLoi file.");
        exit(1);
    }
    int count = 0;
    // 读取所有整数直到文件结束
    while (fscanf(f, "%d", &ptr[count]) == 1) {
        count++;
    }

    fclose(f);
    printf("\n");
    for (int i = 0; i < count; i++) {
        printf("%d\t", ptr[i]);
    }
    free(ptr); // 释放内存,避免泄漏
}

同时修改main函数中的调用:将DocTep(p,n)改为DocTep()。

方案2:先记录偶数数量(严谨可控)

先修改infile函数,写入文件时先记录偶数的总数量,再写入偶数元素:

void infile(int **p,int n)
{
    bool a=false;
    int evenCount = 0;
    // 先统计偶数数量
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < n; j++) {
            if ((p[i][j]) % 2 == 0) {
                evenCount++;
                a=true;
            }
        }   
    FILE *f=fopen("matran.txt","w");
    if (f==NULL)
    {
        printf ("\nLoi file.");
        exit(1);
    }
    if (a) {
        fprintf(f, "%d\n", evenCount); // 先写入偶数数量
        for (int i = 0; i < n; i++) 
            for (int j = 0; j < n; j++) {
                if ((p[i][j]) % 2 == 0) {
                    fprintf(f,"%d\t",p[i][j]);
                }
            }   
        printf ("\nFile da duoc ghi tai ./matran.txt");
    } else {
        fprintf(f, "0"); // 无偶数时写入0
        printf ("\nKhong co so chan trong ma tran");
    }
    fclose(f); // 关闭文件,确保数据写入
}

再修改DocTep函数,先读取数量再读取对应个数的元素:

void DocTep() {
    int *ptr;
    int count;
    FILE *f = fopen("matran.txt", "r");
    if (f == NULL) {
        printf("\nLoi file.");
        exit(1);
    }
    fscanf(f, "%d", &count); // 先读取偶数数量
    if (count == 0) {
        printf("\nKhong co so chan trong file.");
        fclose(f);
        return;
    }
    ptr = (int*)malloc(count*sizeof(int));
    for (int i = 0; i < count; i++) {
        fscanf(f, "%d", &ptr[i]);
    }

    fclose(f);
    printf("\n");
    for (int i = 0; i < count; i++) {
        printf("%d\t", ptr[i]);
    }
    free(ptr);
}

同样修改main函数中的调用为DocTep()。


内容的提问来源于stack exchange,提问作者Đinh Trọng Đạt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:53:12