Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read the last line in a file

Status
Not open for further replies.

sarithat

Programmer
Nov 26, 2002
3
US
hi,
how to read the last line in a file.
my file looks like this

U1,A,200,......
ZZ
email_address

I have to read the last line and insert it into a table.

what I am suppose to do is
read the first 2 lines and insert them into a table 'A'
and read the last line and insert it into a Table 'B'.
The number of lines in my file may vary. so I have to read the last line,
how can I do that.

Thank you
sarithat
 
How about read through the entire file counting the number of lines then go back and grab the last line using the counter? ====================================
I love people. They taste just like
chicken!

 
Hi:

Instead of reading the file to get a line count, why not just say the last line read? At EOF, you should have your last line.

Regards,

Ed
 
Hi

you can do this.

char tmp[1024];

fp = fopen("tmp.dat", "r");

while(!feof(fp))
fgets(tmp, 1024, fp);

prinf("%s", tmp);

On reaching the EOF tmp will have the last line.
So printf will give you the last line.

 
why use 'c' for this?
/bin/tail -1 filename
gives the last line -----------
when they don't ask you anymore, where they are come from, and they don't tell you anymore, where they go ... you'r getting older !
 
I don't know what kind of solution you were looking for, and I don't know how tail does it(I assume by reading the file contents into an array), but I get the impression you were looking for a way to jump to the lastline.

Yes you can do this, but then your problem is describing
a method for only getting the last line when it's size is
not known....this snippet gives you as general idea.
It's still a best guess type thing.

#define len ?

p = getSize(argv[1],&mystat);
printf("Offset = %ld\n %p file pointer\n", p - len, fptr);
p = p - len;

if ((x = fseek(fptr,p,SEEK_SET)) < 0) {
perror(&quot;Fseek()&quot;);
return 1;
} else {
printf(&quot;At %ld\n&quot;, ftell(fptr));
printLast(fptr);

void printLast(FILE *fd) {
int y;
char buf[len];

while ((fgets(buf,len,fd)) != NULL) {
printf(&quot;%s\n&quot;, buf);
}
}

long getSize(char *name, struct stat *sptr) {
int y;

if ((y = stat(name,sptr)) == -1) {
perror(&quot;Stat() could not get file info.&quot;);
exit(0);
}
printf(&quot;File size of %s is %ld\n&quot;, name, (long)sptr->st_size);
return (long)sptr->st_size;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top