开发者

How to read from a file except the last line in C?

开发者 https://www.devze.com 2023-01-10 13:31 出处:网络
I am having a file where i need to read the data and store it into a structure. 10001 john 10002 david

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 o开发者_JS百科f the file).

How to do it in C?

Update : last line will be dynamic.


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.


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 */
}
}


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

Edit:

while (fgets(line, length, file) && !feof(file))
{
   /* process the line */ 
}


int id;
char name[80];

FILE *fp = fopen("data.txt", "r");

while (fscanf(fp, "%d%s[^n]", &id, name) == 2)
{
   /* do something with id and name */ 
}

You don't need to read a line first and then get the data from it. Instead, just read the data you need from the file directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消