0

I have a text file of 257 points like this

3.78135
2.84681
2.81403
2.54225
3.10854
  ...

and I would like to read this data and copy them into an array. With the help of similar answered question I wrote this:

#include<stdio.h>
#include<stdlib.h>

int max_read = 258;
double phi[max_read];
FILE *stream;
stream = fopen("namefile.txt", "r");

if (stream == NULL) {
  print ("! Cannot open file %sn", "namefile.txt\n"); 
  exit(1);
} else{
  int m = 0;
  while(m<max_read) {
    phi[m] = // But I still don't know how write the correct value into the array. 
    m++;
  }
}

I also would like to do this reading-coping procedure until the end of file.

2
  • Do you know about scanf? Do you know there is a fscanf to read from a FILE *? Commented Nov 30, 2018 at 11:19
  • No, sorry, I didn't know :) Commented Nov 30, 2018 at 11:45

1 Answer 1

4

This should do the trick i think.

if (stream == NULL) {
    fprint("! Cannot open file %sn", "namefile.txt\n");
    exit(1);
} else{
    int m = 0;
    while (fscanf(stream, "%lf\n", &phi[m])){
        m++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.