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.
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.
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
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.