Hi Richie - Thanks for the advice. I tried it but couldn't get it to work at all, even though I now think I understand what I'm meant to be doing. As such, I've posted my whole code as it stands and would really appreciate it if you could look at it and see how I can change it to get the annoying x[] and y[] values out of the "read_data_from_file" function!!!
Arrrghhh!!
Cheers!
Code:
/**********************************************************************************/
/* Description: This program will read x and y data values from a given text file */
/* and will calculate and plot the best straight line fit for these data. */
/* Author: Edward King */
/* Group: Yc */
/* Date: 10th March 2006 */
/**********************************************************************************/
#include <stdio.h>
#include <math.h>
#include <grx20.h>
#define MAX_SIZE 128
float x[MAX_SIZE];
float y[MAX_SIZE];
int read_data_from_file(void);
#define NO_FILE -1
int main(int argc, char *argv[])
{
int read_data_from_file(void)
/******************************************************************************/
/* Function Name: read_data_from_file */
/* Description: This function will read x and y data values from a text file. */
/******************************************************************************/
{
// OPENS A FILE:
int i;
FILE *fp;
char file_name[MAX_SIZE]; // Character array for the data filename.
int fs_ret;
// Asks the user to enter the name and location of the data file.
printf("Please enter location and filename of the datafile: ");
scanf("%s",file_name);
printf("\n");
fp = fopen(file_name, "r"); // Opens the file.
if(fp == NULL) // Checks for error in opening file.
{
printf("\nUnable to open file '%s'.\nCheck directory location and filename are correct.\n"
"Please close this program and start again.", file_name);
return NO_FILE; // Stops program if there is an error in opening the file.
}
// READS DATA PAIRS FROM THAT FILE:
i = 0; // Initialises data pair count.
while(i < MAX_SIZE) // Checks that i will fit into the array space.
{
fs_ret = fscanf(fp,"%f%f",&x[i],&y[i]);
// The above reads data from the file.
// 2 floating point numbers are read, x and y.
// Loop continues while 2 data pairs are read and i < 128.
if( fs_ret != 2)
break;
printf("%8.3f\t%8.3f\n",x[i],y[i]); // Prints the data for user.
i++; // Increments the number of pairs read.
} // End loop.
fclose(fp); // Closes the file.
return i; // Retains the number of pairs read.
} // END OF "read_data_from_file" FUNCTION.
int no_of_poi_read;
// USE FUNCTION "read_data_from_file" to return number of pairs read.
no_of_poi_read = read_data_from_file();
if( no_of_poi_read <1)
{
printf("\n\nNO DATA READ.\n\n"); //Defines error message.
}
else
{
//Prints number of pairs read.
printf("\n %d data pairs read from the file. \n\n", no_of_poi_read);
} // End IF statement.
system ("PAUSE");
} // END OF MAIN