从某个偏移量的c ++中读取文本文件

时间:2017-05-12 23:06:30

标签: c++ c matrix

我有一个对角占优矩阵,大小为16000 * 16000.我想为我的实验提取这个矩阵的前n行和n列(例如前100 * 100个单元格),这样提取的矩阵仍然是对角线我试图这样做是:

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

int main()
{

double **Matrix_A;
FILE *fp;   
int global_size = 100;
int offset = 0;

if ((fp = fopen ( "matrix_16000.txt", "r")) == NULL) {
               printf("Can't open input matrix file");
               exit(-1);
             }

 Matrix_A = (double **) malloc(global_size*sizeof(double *));
 for(int irow = 0; irow < global_size; irow++)
    {
    offset =  irow * 16000;
    fseek(fp, offset, SEEK_SET);
    Matrix_A[irow] = (double *) malloc(global_size * sizeof(double));
    for(int icol = 0; icol < global_size; icol++){
        fscanf(fp, "%lf", &Matrix_A[irow][icol]);

        }

    }
    fclose(fp);
    return 0;
 }

这不起作用,因为偏移是不固定的,因为矩阵是随机生成的。知道我的编译器是mpicc

更好的主意

1 个答案:

答案 0 :(得分:1)

你其实很亲密。 fseek没有去上班;相反,扫描到EOL:

 int c;
 Matrix_A = (double **) malloc(global_size*sizeof(double *));
 for(int irow = 0; irow < global_size; irow++) {
    Matrix_A[irow] = (double *) malloc(global_size * sizeof(double));
    for(int icol = 0; icol < global_size; icol++){
        fscanf(fp, "%lf", &Matrix_A[irow][icol]);
    }
    while ((c = fgetc(fp)) != EOF && c != '\r' && c != '\n') {}
 }
 fclose(fp);