Hi,
This is the first part of a program I'm writing. At the moment I'm trying to read from a file and print on the screen, the data shown below (in the format shown), using a linked list. I have managed to get it to work if just column_1 and column_2 are present in the dat file (see program below) but cant figure out how to add to my program to get it to read the whole lot.
Hope that makes sense!
Any help or advice would be greatly appreciated
Thanks a lot.
jamestunic
---------------------------------------
value_1: 10.334
value_2: 25.998
column_1 column_2
0 0
5.623 10.876
10.484 14.988
13.983 18.765
17.342 25.922
20.154 27.245
23.998 29.284
26.655 32.523
29.762 35.924
---------------------------------------
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[101], filename_read[101];
char *line_ptr;
struct node
{
double column_1, column_2;
struct node *next;
};
struct node *first_ptr, *new_ptr, *previous_ptr, *current_ptr;
int no_nodes = 0, no_values = 2;
FILE *input_stream;
fprintf(stdout, "Enter the name of the file to read data from:");
fscanf(stdin, "%s", filename_read);
first_ptr = NULL;
if ((input_stream = fopen(filename_read, "r")) !=NULL)
{
line_ptr = fgets(line, sizeof(line), input_stream);
while((no_values == 2) && ((line_ptr = fgets(line, sizeof(line), input_stream)) != NULL))
{
new_ptr = (struct node *)malloc(sizeof(struct node));
if(first_ptr != NULL)
previous_ptr->next = new_ptr;
else
first_ptr = new_ptr;
new_ptr->next = NULL;
no_values = sscanf(line, "%lf %lf",
&new_ptr->column_1,
&new_ptr->column_2);
previous_ptr = new_ptr;
}
if((first_ptr != NULL) && (no_values == 2))
{
current_ptr = first_ptr;
while(current_ptr->next != NULL)
{
fprintf(stdout, "%lf\t %lf\n", current_ptr->column_1, current_ptr->column_2);
current_ptr = current_ptr->next;
}
fprintf(stdout, "%lf\t %lf\n", current_ptr->column_1, current_ptr->column_2);
}
if((line_ptr != NULL) && (no_values != 2))
fprintf(stdout, "Error reading line %s\n", line);
else
if(line_ptr == NULL)
fprintf(stdout, "End of file found\n");
}
return(0);
}