typedef struct item
{
   int number;
   char package[20];
   char start[20];
   char finish[20];
   int weight;
   int distance;
}ITEM;

int i = 0;
int num = 0;


   while(fscanf(ifp, "%d %s %s %s %d %d", &item[i].number, item[i].package, item[i].start, item[i].finish, &item[i].weight, &item[i].distance) != EOF)
   {
      num++;
	  i++;
   }

	rewind(ifp);
	
	printf("\n\nnum = %d\n\n", num);

I am trying to read in 6 items and store them into a struct while simultaneously checking to see how many lines there are in a file however when I run this I get a segmentation fault.
The strings do not exceed 10 characters so array size isn't an issue.
I can't replace EOF.

Recommended Answers

All 3 Replies

where did you declare array item?

Change the while statement to while( i < sizeof(item)/sizeof(item[0]) && fscanf(...) > 0) . Note: if item array is a paremeter to the function you posted then that sizeof() stuff will not work.

Checking for == 6 (the actual number of conversions you expect for success) would be better than simply >0

Reading a line using fgets(), then parsing the result with sscanf() (or something better) would help as well.
Partial fails of fscanf leave the input stream in a horrible mess.

commented: good points :) +36

Thank you, my problem is solved.

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.