Hi,

Im reading a file, with 2 columns. this is working
such as

1999	5848946
2000	5458445
2001	5757585
2002	7699865
2003	7459758
2004	5797054

as Im reading I want to be able to count how many rows I've read and also add the all values as im reading from the second column, could some help plz
This is the code

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

struct data{

	int x;
	int y;
};
void read_info(void);

int main()
{
	read_info();
}

void read_info(void)
{
	FILE *stocks;
	struct data stock;
	int x;
	char buf[80];
	int total = 0;
	int numberofrecords = 0;
	
	stocks = fopen("banana.dat", "r");
	if(stocks==NULL)
	{
		puts("No data in file");
		return;
	}
	
	while (fgets(buf, 80, stocks) != NULL && !feof(stocks)) 

	{
		sscanf(buf, "%d %d", &stock.x, &stock.y); 
		
		printf("n1 = %d n2 = %d\n", stock.x, stock.y); 
		
		/*numberofrecords = stock.x++;
		total += stock.y; 
               printf("%d %d", numberofrecords, total);*/
	}
	
	
	fclose(stocks);
	
}

All you need to do is keep a count of rows and a running sum of the values. You pretty much had it:

while (fgets(buf, 80, stocks) != NULL && !feof(stocks)) {
  sscanf(buf, "%d %d", &stock.x, &stock.y); 
  printf("n1 = %d n2 = %d\n", stock.x, stock.y); 
  total += stock.y;
  ++numberofrecords;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.