views:

94

answers:

3

I am having a file where i need to read the data and store it into a structure.

10001 john
10002 david
10003 randy
10/10/2010 15:50:55 Updated by : Name

now for the above file i need to read the data from '10001' & 'john' till '10003' & 'randy' except the last line(End of the file).

How to do it in C?

Update : last line will be dynamic.

A: 

read line by line. When you get EOF discard last line.

Edit:

while (fgets(line, length, file) && !feof(file))
{
   /* process the line */ 
}
Andrey
can u help me how to discard the last line.
Guru
My word, how lazy is this guy?
Konrad
adf88
I am not lazy. I am just a beginner in c and not aware of it, thats why asked. I hope its not bad to ask if i am not clear with the concept. Thanks for your reply and please do not say this to others.
Guru
@Guru it is not about C but about programming in general. see the edit.
Andrey
A: 

What would you do if the file didn't have that last line? Presumably in some kind of loop, read each line and save it.

You could just add an "if" before you save, checking whether the line matched your "End of the file".

Generally, with these kind of problems, break the problem down into bits you can understand. Then fits the bits together.

You might also want to consider what you should do if the file looks like

10001 john
10002 david
Silly line in middle of file
10003 randy
End of the file
10003 mr unexepected

Your application should be resilient to weird input.

djna
Also consider empty lines, especially at the end of a file.
adf88
A: 
char line[81];
FILE *f=fopen("file","rt");

while( fgets(line,sizeof line,f) )
{
int tag1;
char tag2[81];
if( 2==sscanf(line,"%d%80s",&tag1,tag2) )
{
/* do anything */
}
}