By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,248 Members | 1,961 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,248 IT Pros & Developers. It's quick & easy.

reading from file and storing in array for Linear Regression (C)

P: 1
Hi There,

I am learning C for university and I am stuck on a question.

I am trying to achieve the following.

1. Read Data from file - This works

Expand|Select|Wrap|Line Numbers
  1. int readfile()
  2. {
  3.     FILE *fptr;
  4.     char filename[15];
  5.     char ch;
  6.  
  7.  
  8.     printf("Enter the filename to be opened \n");
  9.     scanf("%s", filename);
  10.     /*  open the file for reading */
  11.     fptr = fopen(filename, "r");
  12.     if (fptr == NULL)
  13.     {
  14.         printf("Cannot open file \n");
  15.         exit(0);
  16.     }
  17.     ch = fgetc(fptr);
  18.     while (ch != EOF)
  19.     {
  20.        ch = fgetc(fptr);
  21.     }
  22.     fclose(fptr);
  23. }
2. Store data read from file into two arrays (this data is comma delimited).

3. Perform mathematical calculation on the values. - this is done, albeit manual entry at the moment.



The data is stored as per below:

x,y
x1,y1
x2,y2
...
xn,yn

The data also varies in size (so the file could be 30 lines of x and y co-ordinates, or 100).


Any pointers would help.

Thanks
3 Weeks Ago #1
Share this Question
Share on Google+
1 Reply


dev7060
P: 77
fscanf() seems a good option to use here. You can use it like:

Expand|Select|Wrap|Line Numbers
  1. ...
  2. while(fscanf(fptr, "%f,%f", &var1, &var2)==1){
  3.   //Perform calculations
  4. }
  5. ...
  6.  
3 Weeks Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.