while (e=(fread(strr,1,1,fpp)>0) )
has the brackets wrong. It should probably be
while ((e=fread(strr,1,1,fpp))>0)
Besides, your indentation is horrible, and reading/writing 1 byte at a time is very inefficient, and it's wrong to make the fclose
dependent on the if(e>0)
, but neither is the cause of your problem.
Brackets
fread returns the number of records read (in your case, number of bytes, as the record size is 1). It seems like you want to keep reading as long as you get a byte. But your e=(fread..)>0
compares first, then assigns the result of the comparison to e. This is actually ok in this case, because fread can return either 1 or 0 in this specific case - and you want the loop to stop when the return value isn't 1. But generally, this is often a case of an error, because people want the return value in the variable. So your statement just doesn't look right.
Indentation
is fixed now.
read/write 1 byte at a time
is extremely slow, even with the buffering that fread/fwrite provide. Processing chunks of a decently sized buffer is much faster. How big the buffer should be depends on your hardware, but 4K or 8K is a good start to use. Of course, in your specific application, you probably want to give the thread something to do instead of just copying everything in one big chunk.
make fclose dependent on (anything)
is normally wrong unless (anything) == (fopen succeded). When you're finished with the file and don't want to use it anymore, you close it. Period.
In your case, you have a loop while (e ... > 0)
, then an if (e>0)
The part within the if condition will never get executed, as the if will never be reached with e>0
. So you don't close your file anywhere. (Which, in this specific case, is a good thing, because later threads will still access it, but generally, is a mistake).
Threads
Your original post didn't mention the pthread stuff at all.
The way you use it, your first thread will perform the copy operation; while this is happening, the other threads get stuck in the mutex. After the 1st thread releases the mutex, one of the other threads will start trying to copy the file. At this point, the file pointer of the input file is at EOF, where the 1st thread left off; the next thread will try to read more data, fail, and write the un-modified, zero-initialized strr to the backup file. This repeats until the i<lent
part becomes false. Same for all other threads. This is probably where your extra \000
bytes come from. Btw. this shows how important it is to post everything. Your original post discarded the i<lent
part, and said nothing about multiple threads, but these are exactly the key points that lead to your undesired result.