C/File Handaling with c luangage
Expert: Prince M. Premnath - 4/21/2009
QuestionHi Sir,
This is please for me that i have found your touch,
My Question is :
How can i fetch the record or data from already writtened text file. eg. I have ten lined record in text file. now i want only last five record from that text file.
Sir, I am in first sem of MCA[IGNOU]
PLEASE GUIDE ME FOR FURTHER.
AnswerHi Dear HARESH R M!
You can do this without any pain , simply just by the use of fseek() function., lemme summarize few things about this function!
int fseek( FILE *stream, long offset, int origin );
the first argument is typically a file pointer, and the second argument specifies how many bytes to be skipped from the origin (note that origin is the third argument ) the 'origin' should be one among the following value defined in stdio.h header file.
SEEK_SET : seek 'offset' number of bytes from the beginning
SEEK_CURR : seek 'offset' number of bytes from the current position
( Note : you cannot expect the file pointer should be always at the beginning of the file upon every execution of this function, subsequent reads will position the file pointer in a random location inside a file )
SEEK_END : seek 'offset' number of bytes from the end of the file !
( Note : make sure you cannot seek after the end of the file , you supposed to use some negative 'offset' values with this option for reverse seek from the end )
Lets come to the point !
As you have mentioned that you are maintaining data s as records , and obviously all the records should have some fixed length.
assume that each record in your file will be of 10 bytes, in order to read the last 5 records you have to skip the first 5 records ie 5*10 bytes from the beginning of the file.
this can be done using the following fseek() function call !
int RecSize = sizeof(rec); /* in this case let it be 10 bytes */
.
.
.
.
fseek(fp,5*RecSize , SEEK_SET);
/* rest of your code to read the records */
the above seek function call will fix your file pointer after 50 bytes ( ie after 5 records ) from the beginning of your file , from there you can start reading the remaining records!
Get back to me if you wish to have more information regarding any issues related to C
All the best for your first sem exams !
Thanks and Regards !
Prince M. Premnath