jumping to a specific line in a text file

hi everybody!

i need to read a specific line from a text file using C. can any one suggest how to do it.

i m aware abt fread(), fwrite(), fseek()... but using these allows the pointer to be moved 1 character at a time. Is there a way i could jump directly to a line if i know the line number?

i would also like to know how to read rows of a text file and store it in a variable if the type of data in each row is different.

my sample text file looks like this:

username:xyz
login time: 00:00:00
status:0

Thanks!

not so !
with fseek - file pointer can be repositioned anywhere within the file
if the file records are of standard length ( for ex: each and every line of the file contains x chars)

then to switch to nth line
fseek(filePtr, (n * x) + 1, SEEK_CUR);
(assuming \n as the default line separator in the file)
SEEK_CUR is the whence position.

use man fseek you will get the required info

thanx for telling abt fseek().

I agree with you.
but in my case, i know the number of lines in the text file but am not aware of what the length of each line is going to be.

eg:format of the text file

Username : xyz
Machine : 10.101.11.41
Priority : 1
Status : 01
Type :
Time_of_Submittion : 00:00:00
Time_of_Execution : 00:00:00
Time_of_Completion : 00:00:00
Kill : 0
Iteration : 2000/10000

my text file will have a fixed number of rows (eg: 10 in this case). but their values might change with time(eg:username can change to abcd, machine:101.101.101.101...and so on..)
So if i want to read the value of status how do i go about it. to use fseek() i need to know the offset value.

Techincally speaking you cannot escape going for a char by char parsing.
Even if it happens to be a in built function it has to do a search for "\n" character n times to go to n'th line.

For simplicity if you want to totally exclude some portions you can use some unix tools like sed, grep to filter the file contents and then do your stuff :wink:

rishi

You can use fgets() in a loop:

char *fgets(char *s, int n, FILE *stream);

The fgets() function reads characters from the stream into the array pointed to by s, until n-1 characters are read, or a newline character is read and transferred to s, or an end-of-file condition is encountered.

If you want to go to Nth line use fgets() N times. and at the end you can go back to the start of the file using fseek() to start a new read.
--------------------------------------------------
Alternatively you can use combination of head and tail unix commands in shell script to solve your problem.