为什么我无法打开另一个文件?

时间:2016-03-14 19:21:01

标签: c

我正在尝试制作矩阵向量乘法器程序。我完成了矩阵读取,但是当我向程序添加一个新的FILE *它运行但没有任何反应只有我在终端看到黑色。这段代码对我来说很好,但如果我添加这个:FILE * ptr2 = fopen(“abc.dat”,“rt”); fclose(ptr2);它毁了它,但我认为它实际上什么都没有,我想。感谢帮助人员!

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

int main()
{
    int i, j=0, c, d, z=9, sor, oszlop;
    char *temp, *buff;
    double *mtx, *tmp;

    FILE* ptr=fopen("test.dat", "rt");
    mtx=(double*)malloc(12*sizeof(*mtx));
    buff=(char*)malloc(10*sizeof(*buff));

    for(;;) {
        c=fgetc(ptr);

        if(c==' ' || c=='\n' || c=='\t') {
            continue;
        }

        i=0;
        if(isdigit(c) || c=='-' || c=='.') {
            buff[i]=c;
            do {
                d=fgetc(ptr);
                i=i+1;
                if(d==' ' || d=='\n' || d=='\0' || d=='\t') {
                    if(d=='\n') {
                        sor++;
                        break;
                    } else
                        break;
                }
                if(isdigit(d) || d=='-' || d=='.') {
                    buff[i]=d;
                }
            } while(d!=' ');
        }

        mtx[j]=atof(buff);
        j++;
        free(buff);
        if(j>z) {
            tmp=realloc(mtx,(2*j)*sizeof(double));
            if ( tmp != NULL ) {
                mtx=tmp;
            } else {
                printf("Error allocating memory!\n");
                return -1;
            }
        z=(2*j)-3;
        }
        buff=(char*)malloc(sizeof(*buff));

        if(c==EOF) {
            break;
        }
    }

    oszlop=(j-1)/sor;

    for (i = 0; i < sor; i++) {
        for (j = 0; j < oszlop; j++) {
            printf("%lf ", mtx[oszlop * i + j]);
        }
        printf("\n");
    }
    fclose(ptr);
    free(buff);
    free(mtx);

}

1 个答案:

答案 0 :(得分:0)

我改写了这个:

if(j>z) {
        tmp=realloc(mtx,(2*j)*sizeof(double));
        if ( tmp != NULL ) {
            mtx=tmp;
        } else {
            printf("Error allocating memory!\n");
            return -1;
        }

对此,现在它起作用(至少想做什么):

 if(j>z) 
        {
        mtx=realloc(mtx,(2*j)*sizeof(double));
        if(mtx==NULL){
            printf("Error allocating memory!\n");
            return -1;}
        z=(2*j)-3;
        }
大家的帮助从现在开始我会更好地关注每个人都可以阅读它,而不仅仅是我