Help on reading from a file.
I am trying to write a program (in C) for reading grid1.dat and grid2.dat and displays the data it has read on the screen.
I have got as far as the program listed below, it seems to compile fine but doesn’t seem to read correctly as most of the time a runtime error occurs. I’m also unsure how to implement the fprintf statement to get the data to be displayed on the screen.
Any help or advice would be greatly appreciated.
Many thanks
James.
Info stored in grid1.dat:
id x y
1 1.2 0.8
2 1.2 1.0
3 1.2 1.2
4 1.4 0.8
5 1.4 1.0
6 1.4 1.2
7 1.6 0.8
8 1.6 1.0
9 1.6 1.2
Info stored in grid2.dat:
id x y
1 1.2 0.8
2 1.2 1.0
3 1.2 1.2
4 1.4 0.8
5 1.4 1.0
6 1.4 1.2
7 1.6 0.8
8 1.6 1.0
9 1.6 1.2
10 1.8 0.8
11 1.8 1.0
12 1.8 1.2
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[101], filename[101];
char*line_ptr;
struct node
{
int id;
double x, y;
};
struct node node_array[100];
int no_nodes = 0, no_values;
FILE*input_stream;
fprintf(stdout, "Enter file name:");
fscanf(stdin, "%s", filename);
if ((input_stream = fopen(filename, "r")) !=NULL)
{
fgets(line, sizeof(line), input_stream);
while(((line_ptr = fgets(line, sizeof(line), input_stream)) !=NULL)&&
((no_values = sscanf(line, "%d %lf %lf",
&node_array [no_nodes].id,
&node_array [no_nodes].x,
&node_array [no_nodes].y)) = =3)) no_nodes++;
if ((line_ptr !=NULL)&&(no_values !=3))
fprintf(stdout, "Error reading line %s\n", line);
else
if(line_ptr= =NULL)
fprintf(stdout, "End of file found\n");
}
}