I need to get the first number from the file as it gives the maximum elements of the array and then print the arrays. The file is called expt1.txt and contains the following
3
7 4
8 7
9 9
Where 3 is the maximum elements in the array and the left column is the first array which I have called xarray and the right column is the second array which I have called yarray.
I have written a program to find the max number of elements from the file and the two arrays but the program only reads the array on the right hand side. Can anybody see what I'm doing wrong?
Code:
include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define READONLY "r"
#define WRITEONLY "w"
#define MAX_ELEMENTS 100
int main (void)
{
FILE *fp;
char filename[FILENAME_MAX + 1];
double *xarray, *yarray;
int datapoints, i, j;
printf("\n\nWhat file do you wish to analyse: "); /*Opening file*/
scanf("%s", filename);
if((fp = fopen(filename, READONLY)) == NULL){ /*Check that there are no errors in file*/
printf("Cannot open file\n");
exit(EXIT_FAILURE);
}
printf("\n\nReading values from the file %s", filename);
/* Read the number of datapoints in the array from the input file */
fscanf(fp, "%d", &datapoints);
if (datapoints > MAX_ELEMENTS){
fprintf(stderr, "Array size exceeds maximum number of datapoints.\n");
exit(EXIT_FAILURE);
}
printf("\n\nThere are %d data points", datapoints);
xarray = (double *) malloc(datapoints * sizeof(double));
yarray = (double *) malloc(datapoints * sizeof(double));
if((xarray = (double *)malloc(datapoints * sizeof(double))) == NULL ||
(yarray = (double *)malloc(datapoints * sizeof(double))) == NULL){
fprintf(stderr, "Failed to allocate memory.\n");
exit(EXIT_FAILURE);
}
for(i=0; i < datapoints; i++){
fscanf(fp, "%lf", &yarray[i]);
if(!fscanf(fp, "%lf", &yarray[i])){
fprintf(stderr, "Error reading element %d of vector2\n", i+1);
exit(EXIT_FAILURE);
}
printf("\n%lf", yarray[i]);
}
for(i=0; i < datapoints; i++){
fscanf(fp, "%lf", &xarray[i]);
if(!fscanf(fp, "%lf", &xarray[i])){
fprintf(stderr, "Error reading element %d of vector1\n", i+1);
exit(EXIT_FAILURE);
}
printf("\n%lf", xarray[i]);
}
}