scanf - using fscanf in C with varying width files -


i need write program reads in various files , stores information arrays. using doubles perform matrix multiplies. regarding format of files; first line contains size of matrix. next several lines rows of matrix, each element separated space.

format:

<number of rows> <number of columns> <double> <double> ... <double> <double> <double> ... <double> . . . <double> <double> ... <double> 

here couple example files:

3 4 1.20 2.10 4.30 2.10 3.30 3.10 5.20 2.80 1.10 0.60 4.70 4.90 

or

5 5 1.20 2.10 4.30 2.10 6.70 3.30 3.10 5.20 2.80 3.20 1.10 0.60 4.70 4.90 9.10 3.30 3.10 5.20 2.80 3.20 1.10 0.60 4.70 4.90 7.10 

at moment code follows:

float** readfile(char* fp) {     float** matrix = (float**)malloc(m*n*sizeof(float));      fp = fopen(fp, "r");      if (fp == null)     {         fprintf(stderr, "can't open file\n");         exit(1)     }      int = 0;     int m, n;     fscanf(fp, "%d %d", m, n);     while (fscanf(fp, "");     {         i++;     }      fclose(fp);      return matrix; } 

and calling function this:

float** = readfile(argv[1]); 

obviously won't work @ moment because of missing arguments in fscanf while reading file. how can use fscanf read values matrix?

to things, let use 1 dimensional array. here working code you.

#include <stdio.h> #include <stdlib.h>  float* readfile(char* fp, int *m, int *n)/* return dimension defined in file*/ {      file *file = fopen(fp, "r");      if (file == null)     {         fprintf(stderr, "can't open file\n");                 exit(1);     }      int = 0, j = 0;     fscanf(file, "%d %d[^\n]\n", m, n);     float* matrix = (float*)malloc((*m)*(*n)*sizeof(float));      float f;     (i = 0; < *m ; ++i)     (j = 0; j < *n ; ++j)     {        fscanf(file, "%f", (matrix + * (*n) + j));     }       fclose(file);      return matrix; }  int main() {     int m, n, i, j;     float *a = readfile("a.dat", &m, &n); /* named data file a.dat*/      (i = 0; < m ; ++i)         {                 (j = 0; j < n ; ++j)                    printf("%f ", *(a + * n + j));                  printf("\n");         }          free(a); }       /* output */ 1.200000 2.100000 4.300000 2.100000 6.700000 3.300000 3.100000 5.200000 2.800000 3.200000 1.100000 0.600000 4.700000 4.900000 9.100000 3.300000 3.100000 5.200000 2.800000 3.200000 1.100000 0.600000 4.700000 4.900000 7.100000 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -