Problem in reading data from file
Hi, I need help with this C code. basically I'm trying to read a data file that I dont know the number of data, so I am trying to count the number of data and row and trying to create a multidimensional array to store the data. The problem is when I create the array with the number of column and array that the program counted, the number messes up! Please help give me some ideas of why that happen.. any help is appreciated! thank you!
Code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "quicksort.h"
int main(int argc, char *argv[]){
FILE *infile, *outfile;
int i, j, window_width;
float **orig_data;
//Error Checking
if(argc != 3)
{
fprintf(stderr, "ERROR: Not enough arguments!\n");
return 1;
}
int num = atoi(argv[2]);
if (num == 3 || num == 7 || num == 11)
{
window_width = num;
}
else
{
fprintf(stderr,"ERROR: The second argument is not an option!\n");
return 1;
}
float temp;
int count;
//File reading
infile = fopen(argv[1], "r");
if (infile == NULL)
{
fprintf(stderr, "ERROR: The file does not exist!\n");
exit(EXIT_FAILURE);
}
/* Count all data in file */
while(fscanf(infile, "%f", &temp) != EOF)
{
printf("count");
count++;
printf(" %f\n", temp);
}
printf("data %i\n", count);
char tmp;
int row;
rewind(infile);
/* count number of row */
while (fscanf(infile, "%c", &tmp) != EOF)
{
if(tmp == '\n')
{
row++;
}
}
printf("row %i\n", row);
/* find number of column */
int column;
column = count/row;
printf("column %i\n", column);
rewind(infile);
while(fscanf(infile, "%f", &temp) != EOF)
{
printf("%f\n", temp);
}
orig_data = (float **)calloc(row, sizeof(float *));
for (i=0; i<row; i++)
{
orig_data[i]=(float *)calloc(column, sizeof(float));
}
rewind(infile);
float tmp2;
while(fscanf(infile, "%f", &tmp2) != EOF)
{
for(i = 0; i<row; i++)
{
for(j=0; j<column; j++)
{
orig_data[i][j] = tmp2;
}
}
}
for(i = 0; i<row; i++)
{
for(j=0; j<column; j++)
{
printf("%f", orig_data[i][j]);
}
printf("\n");
}
fclose(infile);
}