# Partial read problem with fread()



## vihang (Aug 14, 2009)

Hello,
I am facing partial read problem with fread().
There is a writer process which continously writes data into a binary file in real time.
The reader process reads the data from same file.
In most cases, after some time, fread() starts returning partially read data, even though the return value of fread() matches number of items requested.

e.g.

int nReturnVal = fread (&sRecord,sizeof(sRecord),1,pFilePtr);

where say, sizeof(sRecord) is 68.

Then in the case of partial read, nReturnVal is always 1even though the item was not read completely.

I tried to solve the problem by introducing checksum.

(In the case of partial read, checksum doesnt match.
Then I move file pointer backward by one position and try to read the same record again.)

But once this partial read case occurrs, I never get a proper record again, no matter how many times, I move file pointer backward.
I have to close the file and re-open it again to resume reading...




I face this problem only when the file is being updated by another process at the same time. I have never faced this problem, when there was only reader process running...

I have also tried record level locking using fcntl().
It solved my problem...But it slowed down read & write operations, in turn slowing down my whole system.
I observed that record level locking using fcntl() is almost same as using fflush () after every write...
I dont want to slow down performance. fwrite() when used without fflush() is extremly fast, and i want to perofrm write operation in real time.

I am running my system on Red hat linux (64 bit itanium).
But i have faced this problem even on WinXP.

Is there any way to overcome this problem.???

Thanks & Regards,
Vihang


----------



## Stu_computer (Jul 7, 2005)

hi Vihang, welcome to tsf.

locking using fcntl(). i'll assume you were referring to using a single write lock and not read locks. a better method is to use a semaphore. The Little Book of Semaphores


----------

